Lucas Lazari
Lucas Lazari

Reputation: 119

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?

Upvotes: 0

Views: 35

Answers (1)

Sander van den Oord
Sander van den Oord

Reputation: 12808

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

Upvotes: 1

Related Questions