gpt4 book ai didi

python - Pandas - 无法让 Series.isin 工作

转载 作者:太空宇宙 更新时间:2023-11-03 15:24:46 26 4
gpt4 key购买 nike

我有一个比赛结果的数据框,我想看看比赛的获胜者是否来自与比赛相同的地点。

round_loc 列:

0                       Val d'Allos, France
168 Les Deux Alpes, France
378 Winter Park, CO, USA
499 Whistler, BC, Canada
...

国家栏:

0              France
168 France
378 France
499 Australia
602 France
...

我的代码:

winners_df = df.loc[df['finish_position'] == 1, ['country', 'round_loc']]
hometown_win = winners_df['country'].isin(winners_df['round_loc'])

# Also tried

hometown_win = winners_df['country'].isin(winners_df['round_loc'].values)

print(hometown_win)

我的结果:

0       False
168 False
378 False
499 False
602 False
...

不知道我做错了什么。

winners_df['country'][0] in winners_df['round_loc'][0]

工作正常。我确信我可以用循环来完成它,但我觉得我在这里遗漏了一些东西。

最佳答案

print (winners_df)
round_loc country
0 Val d'Allos, France France
168 Les Deux Alpes, France USA <-changed data sample
378 Winter Park, CO, USA France
499 Whistler, BC, Canada Australia

如果需要检查round_loc列中是否是country列中的一个值:

a = '|'.join(winners_df['country'].unique().tolist())
print (a)
France|USA|Australia

hometown_win = winners_df['round_loc'].str.contains(a)
print(hometown_win)
0 True
168 True
378 True
499 False
Name: round_loc, dtype: bool

如果需要检查round_loc列中是否是country列中的一个值,但每行:

hometown_win = winners_df.apply(lambda x: x['country'] in x['round_loc'],axis=1)
print(hometown_win)
0 True
168 False
378 False
499 False
dtype: bool

关于python - Pandas - 无法让 Series.isin 工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43249131/

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