【问题标题】:How to find out which canidate [Male or Female] scored maximum points in each city? [duplicate]如何找出每个城市中哪个候选人[男性或女性]得分最高? [复制]
【发布时间】:2022-01-09 13:26:11
【问题描述】:

我有这个数据框,我想知道谁在每个城市获得了最高分。

import pandas as pd 

df = pd.DataFrame({"City":["Delhi","Delhi","Mumbai","Mumbai","Lahore","Lahore"],
"Points":[90.1,90.3,94.1,95,89,90.5],
"Gender":["Male","Female","Female","Male","Female","Male"]})

到目前为止,我已经尝试过这个,但这给了我每个城市的性别[男性和女性]的排行榜,

df.groupby(by=["City","Gender"],sort=False)["Points"].max()

我想要一个在每个城市得分最高的候选人[男性或女性]。

【问题讨论】:

    标签: python pandas dataframe pandas-groupby


    【解决方案1】:

    尝试使用仅以“城市”为索引的数据透视表:

    df.pivot_table(values='Points',index=['City'],aggfunc='max')
    

    #输出

            Points
    City          
    Delhi     90.3
    Lahore    90.5
    Mumbai    95.0
    

    如果您想使用 groupby,请随意这样做,但请记住在这里只使用“City”,性别无关紧要

    df.groupby(by=["City"],sort=False)["Points"].max()
    #Output
    City
    Delhi     90.3
    Mumbai    95.0
    Lahore    90.5
    Name: Points, dtype: float64
    

    如果您还想查看性别,请使用:

    df.groupby('City').apply(lambda x: x.sort_values('Points').iloc[-1].reset_index(drop=True))
    

    输出

        0   1   2
    City            
    Delhi   Delhi   90.3    Female
    Lahore  Lahore  90.5    Male
    Mumbai  Mumbai  95.0    Male
    

    【讨论】:

    • 但它并没有告诉我每个城市得分最高的是男孩还是女孩
    • 我编辑了我的原始答案并添加了
    【解决方案2】:

    这个只会给你一张最高分的表格

    import pandas as pd 
    
    df = pd.DataFrame({
        "City":["Delhi","Delhi","Mumbai","Mumbai","Lahore","Lahore"],
        "Points":[90.1,90.3,94.1,95,89,90.5],
        "Gender":["Male","Female","Female","Male","Female","Male"]
    })
    
    df.groupby('City').apply(lambda x: x.sort_values('Points').tail(1)).reset_index(drop=True)
    

    输出:

         City  Points  Gender
    0   Delhi    90.3  Female
    1  Lahore    90.5    Male
    2  Mumbai    95.0    Male
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-11-22
      • 1970-01-01
      • 2016-02-18
      • 2021-04-05
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多