harijay
harijay

Reputation: 11883

How to merge two DataFrames of unequal size based on row value

I have two pandas DataFrames of the type

DataFrame 1

Index   Name    Property1 Property2
0     ("a","b")  1          2
1     ("c","d")  3          4
2     ("e","f")  5          6

And the second one , has common values , but not at the same index ( which I dont care about).

DataFrame 2

Index   Name    Property3 Property4
0     ("g","h")  7          8
1     ("i","j")  9          10
2     ("k","l")  11         12
3     ("a","b")  13         14
4     ("c","d")  15         16
5     ("e","f")  17         18

Is there a way to get these to be combined such that the resultant DataFrame is the common rows with the Name shared between the tables?

i.e Result of pandas operation should be

Result Frame

Index    Name    Property1 Property2 Property3 Property4
0      ("a","b")  1         2           13       14   
1      ("c","d")  3         4           15       16
2      ("e","f")  5         6           17       18

Sorry I am not giving you actual pandas code to create the DataFrames above. But I want to conceptually understand how to join two unequal sized DataFrames with different "indexes" based on a column name . I tried merge and concat and join but dont get the result I want.

Upvotes: 3

Views: 3241

Answers (1)

EdChum
EdChum

Reputation: 393963

A default merge works fine here, assuming your index actually is your index:

In [22]:

df1.merge(df2)
Out[22]:
        Name  Property1  Property2  Property3  Property4
0  ("a","b")          1          2         13         14
1  ("c","d")          3          4         15         16
2  ("e","f")          5          6         17         18

Here the merge looks for common columns and performs an inner merge on those columns.

You can be explicit and specify that you want to merge on the 'Name' column:

df1.merge(df2, on='Name')

but in this case it's not necessary because the only common column is 'Name' anyway.

Upvotes: 3

Related Questions