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

问题描述 投票:0回答:2

我有一个DataFrame,其中包含自1985年以来每一个March Madness游戏的信息。现在我试图通过一轮来计算更高种子的胜利百分比。主DataFrame看起来像这样:

enter image description here

我认为最好的方法是创建单独的功能。第一个是处理得分高于得分的情况.1回归队伍和得分1高于得分回归队伍.1然后在功能结束时追加。下一个需要你做种子.1高于种子和返回团队然后种子高于seed.1并返回team.1然后追加和最后一个函数为那些相等的时候做一个函数

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']])
python pandas function dataframe data-analysis
2个回答
0
投票

您可以通过使用axis=1将lambda函数应用于整个数据框来应用行方式函数。这将允许您获得True/False'low_seed_wins'

使用新的True / False列,您可以获取计数和总和(计数是游戏数量,总和是lower_seed胜利的数量)。使用此功能,您可以将总和除以计数以获得胜率。

这只能起作用,因为你的低级种子队总是在左边。如果它们不是,它会更复杂一些。

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

0
投票

您应该通过检查第一和第二组的两个条件来计算。这将返回一个布尔值,其总和是它为真的个案数。然后只需除以整个数据帧的长度即可获得百分比。没有测试数据很难准确检查

(
    ((tourney['Seed'] > tourney['Seed.1']) & 
     (tourney['Score'] > tourney['Score.1'])) || 
    ((tourney['Seed.1'] > tourney['Seed']) & 
     (tourney['Score.1'] > tourney['Score']))
).sum() / len(tourney)
© www.soinside.com 2019 - 2024. All rights reserved.