python - Pandas: Merging two columns into one with corresponding values

Python - Pandas: Merging two columns into one with corresponding values

To merge two columns into one in a Pandas DataFrame with corresponding values, you can use the + operator or the astype function to concatenate the values. Here's an example:

import pandas as pd # Create a sample DataFrame data = {'Column1': ['A', 'B', 'C'], 'Column2': [1, 2, 3]} df = pd.DataFrame(data) # Merge two columns into a new column df['MergedColumn'] = df['Column1'] + df['Column2'].astype(str) # Display the original DataFrame and the result print("Original DataFrame:") print(df) 

In this example, df['Column1'] + df['Column2'].astype(str) concatenates 'Column1' with the string representation of 'Column2'. Adjust the concatenation logic based on your requirements.

Ensure you have Pandas installed:

pip install pandas 

Replace the sample data in the data dictionary with your actual data. The resulting DataFrame (df) will contain a new column named 'MergedColumn' with the merged values from 'Column1' and 'Column2'.

Examples

  1. Pandas merge two columns into one with a separator:

    import pandas as pd df = pd.DataFrame({'Name': ['Alice', 'Bob', 'Charlie'], 'Age': [25, 30, 22]}) # Merge 'Name' and 'Age' columns into a new column with a separator df['Name_Age'] = df['Name'] + '_' + df['Age'].astype(str) 

    Description: This code merges two columns ('Name' and 'Age') in a DataFrame (df) into a new column ('Name_Age') with an underscore separator.

  2. Pandas merge two columns into one with a space:

    import pandas as pd df = pd.DataFrame({'First_Name': ['Alice', 'Bob', 'Charlie'], 'Last_Name': ['Smith', 'Johnson', 'Brown']}) # Merge 'First_Name' and 'Last_Name' columns into a new column with a space separator df['Full_Name'] = df['First_Name'] + ' ' + df['Last_Name'] 

    Description: This code merges two columns ('First_Name' and 'Last_Name') in a DataFrame (df) into a new column ('Full_Name') with a space separator.

  3. Pandas merge two columns into one using format:

    import pandas as pd df = pd.DataFrame({'City': ['New York', 'San Francisco', 'Los Angeles'], 'State': ['NY', 'CA', 'CA']}) # Merge 'City' and 'State' columns into a new column using format df['Location'] = df.apply(lambda row: '{} ({})'.format(row['City'], row['State']), axis=1) 

    Description: This code merges two columns ('City' and 'State') in a DataFrame (df) into a new column ('Location') using the format function.

  4. Pandas merge two columns into one with a custom function:

    import pandas as pd df = pd.DataFrame({'Category': ['Fruit', 'Vegetable', 'Grain'], 'Type': ['Apple', 'Carrot', 'Rice']}) # Merge 'Category' and 'Type' columns into a new column using a custom function df['Food'] = df.apply(lambda row: row['Type'] + ' (' + row['Category'] + ')', axis=1) 

    Description: This code merges two columns ('Category' and 'Type') in a DataFrame (df) into a new column ('Food') using a custom function.

  5. Pandas merge two columns into one with a hyphen separator:

    import pandas as pd df = pd.DataFrame({'Prefix': ['Mr', 'Ms', 'Dr'], 'Name': ['Smith', 'Johnson', 'Brown']}) # Merge 'Prefix' and 'Name' columns into a new column with a hyphen separator df['Full_Name'] = df['Prefix'] + '-' + df['Name'] 

    Description: This code merges two columns ('Prefix' and 'Name') in a DataFrame (df) into a new column ('Full_Name') with a hyphen separator.

  6. Pandas merge two columns into one with a custom delimiter:

    import pandas as pd df = pd.DataFrame({'Part1': ['A', 'B', 'C'], 'Part2': ['1', '2', '3']}) # Merge 'Part1' and 'Part2' columns into a new column with a custom delimiter (e.g., ':') df['Combined'] = df['Part1'] + ':' + df['Part2'] 

    Description: This code merges two columns ('Part1' and 'Part2') in a DataFrame (df) into a new column ('Combined') with a custom delimiter (e.g., ':').

  7. Pandas merge two columns into one with conditional concatenation:

    import pandas as pd df = pd.DataFrame({'First_Name': ['Alice', 'Bob', 'Charlie'], 'Last_Name': ['Smith', 'Johnson', '']}) # Merge 'First_Name' and 'Last_Name' columns into a new column with conditional concatenation df['Full_Name'] = df.apply(lambda row: row['First_Name'] if row['Last_Name'] == '' else row['First_Name'] + ' ' + row['Last_Name'], axis=1) 

    Description: This code merges two columns ('First_Name' and 'Last_Name') in a DataFrame (df) into a new column ('Full_Name') with conditional concatenation based on the presence of values in 'Last_Name'.

  8. Pandas merge two columns into one and handle NaN values:

    import pandas as pd df = pd.DataFrame({'Color1': ['Red', 'Blue', 'Green'], 'Color2': [None, 'Yellow', 'Orange']}) # Merge 'Color1' and 'Color2' columns into a new column and handle NaN values df['Combined_Color'] = df['Color1'].fillna('') + df['Color2'].fillna('') 

    Description: This code merges two columns ('Color1' and 'Color2') in a DataFrame (df) into a new column ('Combined_Color') and handles NaN values by using fillna('').

  9. Pandas merge two columns into one with a line break:

    import pandas as pd df = pd.DataFrame({'Title': ['Introduction', 'Methods', 'Results'], 'Content': ['Lorem ipsum', 'Dolor sit', 'Consectetur adipiscing']}) # Merge 'Title' and 'Content' columns into a new column with a line break df['Section'] = df['Title'] + '\n' + df['Content'] 

    Description: This code merges two columns ('Title' and 'Content') in a DataFrame (df) into a new column ('Section') with a line break.

  10. Pandas merge two columns into one using a lambda function:

    import pandas as pd df = pd.DataFrame({'Prefix': ['Mr', 'Ms', 'Dr'], 'Name': ['Smith', 'Johnson', 'Brown']}) # Merge 'Prefix' and 'Name' columns into a new column using a lambda function df['Full_Name'] = df.apply(lambda row: f"{row['Prefix']} {row['Name']}", axis=1) 

    Description: This code merges two columns ('Prefix' and 'Name') in a DataFrame (df) into a new column ('Full_Name') using a lambda function and formatted string.


More Tags

web-scraping vaadin web-console ecmascript-6 mean-stack unique-id internationalization gradle uislider ng-submit

More Programming Questions

More Other animals Calculators

More Math Calculators

More Fitness-Health Calculators

More Livestock Calculators