gpt4 book ai didi

python - Pandas - 合并包含一些空值的列

转载 作者:行者123 更新时间:2023-12-01 08:51:29 25 4
gpt4 key购买 nike

我有 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')

如何合并这些数据框?

最佳答案

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

关于python - Pandas - 合并包含一些空值的列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53085438/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com