计算DataFram中满足多个条件的值的百分比

2024-05-20 01:06:36 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个数据框,里面有1985年以来每一个三月疯狂游戏的信息。现在我试着计算高一号种子每轮获胜的百分比。主数据帧如下所示:

enter image description here

我认为最好的方法是创建单独的函数。第一种方法处理得分高于分数的情况。1返回团队,当得分.1高于分数时返回团队。1然后在函数末尾附加这些值。下一个为需要u做seed.1比seed高,然后返回team高于seed.1和return team.1,然后append和last函数为相等时生成一个函数

def func1(x):
    if tourney.loc[tourney['Score']] > tourney.loc[tourney['Score.1']]:
        return tourney.loc[tourney['Team']]
    elif tourney.loc[tourney['Score.1']] > tourney.loc[tourney['Score']]:
        return tourney.loc[tourney['Team.1']]

func1(tourney.loc[tourney['Score']])

Tags: 数据方法函数信息游戏return情况团队
2条回答

你应该通过检查第一组和第二组的两个条件来计算这个值。这将返回一个布尔值,其和为真的情况数。然后除以整个数据帧的长度得到百分比。没有测试数据,很难准确地检查

(
    ((tourney['Seed'] > tourney['Seed.1']) & 
     (tourney['Score'] > tourney['Score.1'])) || 
    ((tourney['Seed.1'] > tourney['Seed']) & 
     (tourney['Score.1'] > tourney['Score']))
).sum() / len(tourney)

通过对整个数据帧应用lambda函数,可以应用行函数,并使用axis=1。这将允许您获得True/False'low_seed_wins'。在

你可以计算出新的游戏数(如果是真的,你可以计算出新游戏的数量)。用这个你可以用总数除以计数得到胜率。在

这只是因为你的低种子队总是在左边。如果不是更复杂的话。在

import pandas as pd
df = pd.DataFrame([[1987,3,1,74,68,5],[1987,3,2,87,81,6],[1987,4,1,84,81,2],[1987,4,1,75,79,2]], columns=['Year','Round','Seed','Score','Score.1','Seed.1'])

df['low_seed_wins'] = df.apply(lambda row: row['Score'] > row['Score.1'], axis=1)

df = df.groupby(['Year','Round'])['low_seed_wins'].agg(['count','sum']).reset_index()

df['ratio'] = df['sum'] / df['count']

df.head()


Year    Round   count   sum     ratio
0   1987    3   2       2.0     1.0
1   1987    4   2       1.0     0.5

相关问题 更多 >