2017-04-06 86 views
1

我有一个比赛结果的数据框,我试图看看比赛的获胜者是否来自与比赛相同的位置。熊猫 - 无法获得Series.isin的工作

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] 

工作正常。我确信我可以用循环做,但我觉得我在这里错过了一些东西。

+3

这不行'isin'正在寻找完全匹配,你想比较每一行并使用'contains'来测试这里的会员资格/匹配 – EdChum

回答

1
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 
+0

啊,这很有道理。如果在法国(round_loc)有一场比赛没有被法国(国家)的某个选手夺冠,因为每排都有一名赛车手,那么这里看起来可能会有问题。 – moto

+0

是的,确切地说。如果我的回答很有帮助,请不要忘记[接受](http://meta.stackexchange.com/a/5235/295067)它。谢谢。 – jezrael

+0

非常完美!谢谢!我不知道你可以检查这样的轴上的所有项目! – moto