【问题标题】:Counting the number of rows having values greater than particular row after grouping in a dataframe在数据帧中分组后计算值大于特定行的行数
【发布时间】:2022-01-17 06:17:13
【问题描述】:

我有一个包含重要城市人口的数据框。 Dataframe image

它包含来自不同国家的城市。在特定国家的所有城市中,只有一个城市被视为主要城市(在“首都”列中提到)。我需要找出人口大于主要城市的城市数量。请提供一种解决方案?

【问题讨论】:

    标签: python pandas jupyter-notebook data-analysis


    【解决方案1】:

    用途:

    #test primary
    m = df['capital'].eq('primary')
    
    #get dict for primary population
    d = df[m].set_index('country')['population'].to_dict()
    
    #filter not primary
    df1 = df[~m].copy()
    
    #compare non primary population with primary by map and count with sum
    out = df1['population'].gt(df1['country'].map(d)).sum()
    
    #filter compare rows if necessary
    df2 = df1[df1['population'].gt(df1['country'].map(d))]
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-05-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-05-21
      相关资源
      最近更新 更多