Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add suffix to all column names when using pandas.merge()

Tags:

python

pandas

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?

like image 690
Martin Preusse Avatar asked Feb 13 '19 15:02

Martin Preusse


People also ask

How do I add a suffix to all column names in Pandas?

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.

How do I merge column names in Pandas?

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.


1 Answers

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')
like image 102
iacob Avatar answered Oct 24 '22 17:10

iacob