combine two column fron two dataframe with a separator in python

To combine two columns from two dataframes with a separator in pandas, you can use the merge() or join() function in python.

Assuming you have two dataframes df1 and df2, and you want to combine the columns 'col1' from df1 and 'col2' from df2 with a separator '-', you can do the following:

main.py
import pandas as pd

# create sample dataframes
data1 = {'id': [1, 2, 3], 'col1': ['A', 'B', 'C']}
df1 = pd.DataFrame(data1)
data2 = {'id': [1, 2, 3], 'col2': ['x', 'y', 'z']}
df2 = pd.DataFrame(data2)

# merge or join the dataframes on the 'id' column
merged_df = df1.merge(df2, on='id')

# combine the columns 'col1' and 'col2' with a separator '-'
merged_df['combined_col'] = merged_df['col1'] + '-' + merged_df['col2']

# drop the original columns 'col1' and 'col2' if needed
merged_df = merged_df.drop(['col1', 'col2'], axis=1)

print(merged_df)
551 chars
19 lines

This will output the following merged dataframe with the combined column:

main.py
   id combined_col
0   1          A-x
1   2          B-y
2   3          C-z
76 chars
5 lines

gistlibby LogSnag