python pandas dataframe合并或连接数据帧

时间:2016-10-19 11:26:43

标签: python pandas join dataframe merge

我想帮助你

如果我有一个pandas数据帧合并

第一个数据帧是

sigmoid_func(x, parameters):
    if parameter outside multiple bounds:
        return 1.0E10 * len(x) # very large number
    else:
        return sigmoid value

形状是38654rows x 14列

第二个数据帧是

D = { Year, Age, Location, column1, column2... }
      2013, 20 , america, ..., ...
      2013, 35, usa, ..., ...
      2011, 32, asia, ..., ...
      2008, 45, japan, ..., ...

形状是96rows x 7列

我想合并或加入两个不同的数据帧。 我该怎么办?

感谢

1 个答案:

答案 0 :(得分:4)

如果需要在列how='left'Year上保持联接,则需要merge带参数Location的IIUC:

print (df1)
   Year  Age Location  column1  column2
0  2013   20  america        7        5
1  2008   35      usa        8        1
2  2011   32     asia        9        3
3  2008   45    japan        7        1

print (df2)
   Year Location  column1  column2
0  2008      usa        8        9
1  2008      usa        7        2
2  2009     asia        8        2
3  2009     asia        0        1
4  2010    japna        9        3

df = pd.merge(df1,df2, on=['Year','Location'], how='left')
print (df)
   Year  Age Location  column1_x  column2_x  column1_y  column2_y
0  2013   20  america          7          5        NaN        NaN
1  2008   35      usa          8          1        8.0        9.0
2  2008   35      usa          8          1        7.0        2.0
3  2011   32     asia          9          3        NaN        NaN
4  2008   45    japan          7          1        NaN        NaN

您还可以查看documentation