python pandas数据帧合并或连接datafram

2024-03-29 14:31:25 发布

您现在位置:Python中文网/ 问答频道 /正文

我想帮你

如果我有熊猫数据帧合并

第一个数据帧是

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

形状为38654行x 14列

第二个数据帧是

^{pr2}$

形状为96行x 7列

我想合并或连接两个不同的数据帧。 我该怎么做?

谢谢


Tags: 数据agelocationyear形状column1usaasia
1条回答
网友
1楼 · 发布于 2024-03-29 14:31:25

IIUC如果需要对列YearLocation进行左连接,则需要使用参数how='left'的{a1}:

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。在

相关问题 更多 >