gpt4 book ai didi

python - 使用多个条件遍历数据框的正确方法

转载 作者:行者123 更新时间:2023-12-01 12:49:01 26 4
gpt4 key购买 nike

我有一个足球比赛数据集作为 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

我想在列表字典中按团队跟踪结果:
{'利物浦':[W,W, ... ,W],'西汉姆':[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 answernp.wherenp.select ,但我认为它不适用于这种情况,在这种情况下,我想根据每行的条件结果做一些事情,使用行中的条目作为键。

感觉好像迭代是这里唯一的解决方案,我相信 Pandas 会支持这样的东西,但我不知道如何搜索它。

最佳答案

这是一种使用 DataFrame.melt 的方法, numpy.selectDataFrame.groupby使用 list 聚合。

注意我在您的示例数据中添加了“Liverpool”和“Norwich City”之间的重赛,以显示输出应该如何显示团队出现不止一次:

#Setup
df = pd.DataFrame({'Home': ['Liverpool', 'West Ham', 'AFC Bournemouth', 'Burnley', 'Crystal Palace', 'Norwich City'], 'Away': ['Norwich City', 'Man City', 'Sheffield United', 'Southampton', 'Everton', 'Liverpool'], 'Result': ['Liverpool', 'Man City', 'Draw', 'Burnley', 'Draw', 'Norwich City'], 'HG': [4, 0, 1, 3, 0, 4], 'AG': [1, 5, 1, 0, 0, 1]})

# Restructure the DataFrame into a long-form with "Melt"
df_melted = (df.reset_index()
.melt(id_vars=['Result', 'index'],
value_vars=['Home', 'Away'])
.sort_values('index')) # This maintains the match order of original df

# Use numpy.select to create your conditions and choices ('W', 'L' or 'D')
df_melted['outcome'] = np.select(
condlist=[df_melted['Result'] == 'Draw',
df_melted['Result'] == df_melted['value'],
df_melted['Result'] != df_melted['value']],
choicelist=['D', 'W', 'L'])


# Groupby team agg with list and return output as dict
df_melted.groupby('value', sort=False)['outcome'].apply(list).to_dict()

[输出]

{'Liverpool': ['W', 'L'],
'Norwich City': ['L', 'W'],
'West Ham': ['L'],
'Man City': ['W'],
'AFC Bournemouth': ['D'],
'Sheffield United': ['D'],
'Burnley': ['W'],
'Southampton': ['L'],
'Crystal Palace': ['D'],
'Everton': ['D']}

关于python - 使用多个条件遍历数据框的正确方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59893471/

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