简体   繁体   中英

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?

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)])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM