36

I am new with pandas and I am trying to join two dataframes based on the equality of one specific column. For example suppose that I have the followings:

df1
A    B    C
1    2    3
2    2    2

df2
A    B    C
5    6    7
2    8    9

Both dataframes have the same columns and the value of only one column (say A) might be equal. What I want as output is this:

df3
A    B    C   B    C
2    8    9   2    2

The values for column 'A' are unique in both dataframes.

Thanks

0

2 Answers 2

43
pd.concat([df1.set_index('A'),df2.set_index('A')], axis=1, join='inner')

If you wish to maintain column A as a non-index, then:

pd.concat([df1.set_index('A'),df2.set_index('A')], axis=1, join='inner').reset_index()
Sign up to request clarification or add additional context in comments.

3 Comments

With this good method - A becomes the index. This may be what the OP wants, but you might also offer use of reset_index to turn it into a column if that's what is wanted.
Sure, the index can be reset by adding .reset_index() at the end. pd.concat([df1.set_index('A'),df2.set_index('A')], axis=1, join='inner').reset_index()
yup - that's what I was getting at :)
37

Alternatively, you could just do:

df3 = df1.merge(df2, on='A', how='inner', suffixes=('_1', '_2'))

And then you can keep track of each value's origin

4 Comments

What does suffixes do?
addes a suffix to each column name so that you're not left with e.g. two columns called "B". When you have duplicate column names, you get very unexpected behavior with say, df3['B'].apply(lambda x: ...) since now df['B'] is a DataFrame and not a Series.
Awesome. That actually helps alot
Works great. tnx :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.