简体   繁体   中英

Merging two pandas dataframes with common data

Consider this data:

  INF  CTR  Time 
A  1    8     3
B  5    1     3
C  3    2     3

And I have another set of data with the same elements, but different column names:

  INF2  CTR2  Time 
A  3    1     3
B  6    4     3
C  1    7     3

I need to merge theses data like this:

  INF  CTR  INF2  CTR2  Time 
A  1    8     3    1     3
B  5    1     6    4     3
C  3    2     1    7     3

How can I do it?

When you want to join on indexes use .join() , otherwise pd.merge() :

df1.join(df2[['INF2', 'CTR2']])

Merging on indexes looks like this:

pd.merge(
    df1, 
    df2[['INF2', 'CTR2']], 
    left_index=True, 
    right_index=True,
)

Please also check out this great post on merging in pandas:
Pandas Merging 101

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