如何使此代码成为更多惯用的熊猫?

时间:2019-01-14 07:05:41

标签: pandas idioms

还有一个广泛的问题,但是我不确定如何通过其他途径获得有关如何改进此代码的指针。

我有一个数据框,其中包含投注赔率和游戏结果,并且我想计算投资某个团队的支出。

我现在拥有的代码可以正常工作,但是我觉得只要依靠apply方法并放入Python,熊猫Pandas就可以完成很多工作。

这是数据框的外观: enter image description here

这是我的代码:

def compute_payout(odds, amount=1):
    if odds < 0:
        return amount/(-1.0 * odds/100.0)
    elif odds > 0:
        return amount/(100.0/odds)

def game_payout(row, team_name):
    if row['home_team'] == team_name:
        if row['home_score'] > row['away_score']:
            return compute_payout(row['home_odds'])
        else:
            return -1
    elif row['away_team'] == team_name:
        if row['away_score'] > row['home_score']:
            return compute_payout(row['away_odds'])
        else:
            return -1

payout = df.apply(lambda row: game_payout(row, team_name), axis=1)

任何建议深表感谢!

1 个答案:

答案 0 :(得分:2)

numpy.select与由&链接的条件用于bitwise AND,将~链接到反布尔掩码:

m11 = df['home_team'] == team_name
m21 = df['away_team'] == team_name

m12 = df['home_score'] > df['away_score']
m22 = df['home_score'] < df['away_score']

vals = [df['home_odds'].apply(compute_payout), -1, df['away_odds'].apply(compute_payout), -1]
payout = np.select([m11 & m12, m11 & ~m12, m21 & m22, m21 & ~m22], vals, default=np.nan)