【问题标题】:Goals for and Goals Against I want to return result (Win, Draw, Loss). Pandas Python目标和目标我想要返回结果(赢、平、输)。熊猫蟒
【发布时间】:2022-01-05 22:40:53
【问题描述】:

尝试根据 GF 和 GA 创建一个新列“结果”。想知道如何通过定义函数和条件语句来做到这一点。以下是我对一行的初步尝试,但无法弄清楚我将如何应用于所有行,非常感谢您的帮助!

Date Venue Opponent GF GA
08-19-2017 H Crystal Palace 1 0
08-27-2017 H Arsenal FC 4 0
09-16-2017 H Burnley FC 1 1
10-14-2017 H Manchester United 0 0
10-28-2017 H Huddersfield Town 3 0

原始输入:

df = pd.DataFrame({'Date': ['08-19-2017', '08-27-2017', '09-16-2017', '10-14-2017', '10-28-2017'],
                   'Venue': ['H', 'H', 'H', 'H', 'H'],
                   'Opponent': ['Crystal Palace', 'Arsenal FC', 'Burnley FC', 'Manchester United', 'Huddersfield Town'],
                   'GF': [1, 4, 1, 0, 3],
                   'GA': [0, 0, 1, 0, 0]})

我的尝试:

    # for one row (match)
gf = df[0, 3]
ga = df[0, 4]
        
if gf > ga:
    print('W')
elif gf < ga:
    print('L')
else:
    print('D')
    

输出:W

将其应用于所有行,我将如何基于以下解决方案:

 ```# create a function
def win_draw_loss():
    
if df['GF'] > df['GA']:
    print('W')
elif mo_rec['GF'].sum() < mo_rec['GA'].sum():
    print('L')
else:
    print('D')

# making the new pandas column
df['results'] =  ```

【问题讨论】:

    标签: python pandas dataframe analytics


    【解决方案1】:

    您可以稍微更正您的 win_draw_loss 函数并将其应用于 DataFrame df 的每一行。下面更正的函数的问题是 win_draw_loss 如果要将其应用于 DataFrame,则必须将行数据作为参数,因此您的评估也需要针对行数据。

    def win_draw_loss(x):
        
        if x['GF'] > x['GA']:
            return 'W'
        elif x['GF'] < x['GA']:
            return 'L'
        else:
            return 'D'
    
    df['Results'] = df.apply(win_draw_loss, axis=1)
    

    你也可以使用np.select:

    import numpy as np
    df['Results'] = np.select([df['GF'] > df['GA'], df['GF'] < df['GA']], ['W', 'L'], 'D')
    

    输出:

            Date Venue           Opponent  GF  GA  Results
    0  08-19-2017     H     Crystal Palace   1   0       W
    1  08-27-2017     H         Arsenal FC   4   0       W
    2  09-16-2017     H         Burnley FC   1   1       D
    3  10-14-2017     H  Manchester United   0   0       D
    4  10-28-2017     H  Huddersfield Town   3   0       W
    

    【讨论】:

    • 感谢您分享函数知识。我将把它应用到我的个人项目中。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-11-25
    • 2012-05-15
    • 2020-11-08
    • 1970-01-01
    • 1970-01-01
    • 2020-05-12
    • 1970-01-01
    相关资源
    最近更新 更多