gpt4 book ai didi

python - 如果在右侧数据框中找不到左侧数据框中的值,如何使用合并返回 NaN 在 pandas 中执行 VLOOKUP?

转载 作者:太空宇宙 更新时间:2023-11-04 08:29:25 24 4
gpt4 key购买 nike

所以第一个(也是左边的)数据框是:

Name
Brees
Brady
Rodgers
Mahomes

第二个(也是右边的)数据框是:

Name
Brees
Brady
Wilson
Mahomes

我想回去

Name
Brees
Brady
NaN
Mahomes

我使用代码 pd.merge(df,df1,on="Name",how='left'),但它返回:

Name
Brees
Brady
Rodgers
Mahomes

本质上,返回的是左边的dataframe

最佳答案

您可以使用 pd.Series.where使用通过 isin 计算的 bool 级数:

df1['Name'] = df1.where(df1['Name'].isin(df2['Name']))

print(df1)
# Name
# 0 Brees
# 1 Brady
# 2 NaN
# 3 Mahomes

关于python - 如果在右侧数据框中找不到左侧数据框中的值,如何使用合并返回 NaN 在 pandas 中执行 VLOOKUP?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54165225/

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