熊猫-合并包含一些空值的列

时间:2018-10-31 14:14:20

标签: python pandas

我有2个数据框-城市和体育场。我要合并它们

cities
     Name   Stadium
0     c1      a
1     c2     NaN
2     c3     NaN
3     c4      b

stadiums
      Name     Capacity Type Col4 Col5
0       a        1       1    1     4
1       b        3       2    2     5
2       c        3       1    1     6

Output:
     Name   Stadium Capacity Type
0     c1      a       1       1
1     c2     NaN     NaN     NaN
2     c3     NaN     NaN     NaN
3     c4      b       3       2

当我将它们与以下语句之一合并时,会得到其他行:

cities = pd.merge(cities,stadiums[['Name','Capacity','Type']],left_on='Stadium',right_on='name',how='left')

cities = pd.merge(cities,stadiums[['Name','Capacity','Type']],left_on='Stadium',right_on='name',how='outer')

如何合并这些数据框?

2 个答案:

答案 0 :(得分:1)

您的问题是您正在执行外部合并(how='outer'),这意味着两个数据帧中的所有行都包含在输出中。如果您只想匹配cities数据框中的行,请尝试使用how='left'

答案 1 :(得分:0)

outerleft

cities = pd.merge(cities,stadiums[['Name','Capacity','Type']],left_on='Stadium',right_on='Name',how='left')
cities
Out[157]: 
  Name_x Stadium Name_y  Capacity  Type
0     c1       a      a       1.0   1.0
1     c2     NaN    NaN       NaN   NaN
2     c3     NaN    NaN       NaN   NaN
3     c4       b      b       3.0   2.0