【发布时间】:2020-01-24 09:20:32
【问题描述】:
我有一个足球比赛数据集作为 Pandas 数据框,格式如下:
Home Away Result HG AG
0 Liverpool Norwich City Liverpool 4 1
1 West Ham Man City Man City 0 5
2 AFC Bournemouth Sheffield United Draw 1 1
3 Burnley Southampton Burnley 3 0
4 Crystal Palace Everton Draw 0 0
我想在列表字典中按团队跟踪结果:{'Liverpool': [W,W, ... ,W], 'West Ham': [W, D, L, ... ], ... } 等。
我的方法自然是用条件遍历所有行(下面是伪代码):
if df.Result == 'Draw':
dict[df[Home]].append('D')
dict[df[Away]].append('D')
elif df.Home == df.Result:
dict[df[Home]].append('W')
dict[df[Away]].append('L')
else:
dict[df[Home]].append('L')
dict[df[Away]].append('W')
我相信我可以使用df.iterrows() 做到这一点,但我知道这不是 Pandas 所希望的一般方法。有没有办法在利用 Pandas DataFrames 的强大功能的同时进行这种操作?我已经看到 df.Home == df.Result 返回一系列 True/False 值,但我不知道如何利用它或将其扩展到上述多个条件。
我还看到了 this answer 中的 np.where 和 np.select,但我不认为它适用于我想根据每行条件的结果做某事的情况,使用行中的条目作为键。
感觉好像迭代是这里唯一的解决方案,我确信 Pandas 会支持这样的东西,但我不知道如何搜索它。
【问题讨论】: