The pandas merge()
function allows to add suffixes to overlapping column names:
merged = table1.merge(table2, left_on='header', right_on='header',
suffixes=('table1', 'table2'))
However, this adds suffixes only to the overlapping columns. Is it possible to add a suffix to all columns except the merge column?
To add a string after each column label of DataFrame in Pandas, call add_suffix() method on this DataFrame, and pass the suffix string as argument to add_suffix() method.
It is possible to join the different columns is using concat() method. DataFrame: It is dataframe name. axis: 0 refers to the row axis and1 refers the column axis. join: Type of join.
You could add the suffixes to the tables before merging, and revert the merge column names:
table1 = table1.add_suffix('table1')
table1 = table1.rename(index=str, columns={'headertable1':'header'})
table2 = table2.add_suffix('table2')
table2 = table2.rename(index=str, columns={'headertable2':'header'})
merged = table1.merge(table2, on='header')
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With