tumbleweed
tumbleweed

Reputation: 4630

How to replace pandas columns with the same name in to another dataframe?

I have the following large pandas dataframe A:

A     B    ...   C
cat   cotsco... apple
cat   walmart... google
dog   sears...   google
dog   homemart... amazon
...
fish  walmart... microsoft

An pandas dataframe B:

A    B ...     D
1.2  0.0  ...  1
3.3  9.1 ...   2
4.5  1.2 ...   5
6.79 1.222 ... 4
...
9.9  1.3 ...   8

How can I replace all the columns that have the same name in pandas dataframe A in B?

A     B    ...      C     D
cat   cotsco...   apple   1
cat   walmart...  google  2
dog   sears...    google  5
dog   homemart... amazon  4
...
fish  walmart... microsoft 8

I know that I can do df1['D'] = df2['D']. However, I have 2000 columns like this. Is there another handy way of doing this?

Upvotes: 3

Views: 3608

Answers (1)

jezrael
jezrael

Reputation: 862511

Use assign only:

df1['D'] = df2['D']

If need add multiple columns with different columns names:

df = pd.concat([df1, df2[df2.columns.difference(df1.columns)]], axis=1)

Or:

df = df1.join(df2[df2.columns.difference(df1.columns)])

Upvotes: 3

Related Questions