Reputation: 11
I need to concatenate 2 pandas DataFrames by 2 colunms. Example:
df1 = pd.DataFrame({'col1':[1,2,3],'col2':[11,22,33]})
df2 = pd.DataFrame({'col1':[1,2,3,4,5,6],'col2':[11,22,33,44,55,66],'col3':[111,222,333,444,555,666]})
df2
col1 col2 col3
1 11 111
2 22 222
3 33 333
4 44 444
5 55 555
6 66 666
df1
col1 col2
1 11
2 22
3 33
Result:
col1 col2 col3
1 11 111
2 22 222
3 33 333
Here col1
and col2
used as index for values form df2.col3
.
Thanks.
(Sorry, my English is bad)
Upvotes: 0
Views: 139
Reputation: 82755
You can use df.merge
Ex:
import pandas as pd
df1 = pd.DataFrame({'col1':[1,2,3],'col2':[11,22,33]})
df2 = pd.DataFrame({'col1':[1,2,3,4,5,6],'col2':[11,22,33,44,55,66],'col3':[111,222,333,444,555,666]})
print( df2.merge(df1, on=["col1", "col2"]) )
Output:
col1 col2 col3
0 1 11 111
1 2 22 222
2 3 33 333
Upvotes: 1