【问题标题】:Count the number of Occurrence of Values based on another column根据另一列计算值的出现次数
【发布时间】:2016-09-21 13:28:59
【问题描述】:

我有一个关于根据其他列的总和创建熊猫数据框的问题。

例如,我有这个数据框

 Country    |    Accident
 England           Car
 England           Car
 England           Car
  USA              Car
  USA              Bike
  USA              Plane
 Germany           Car
 Thailand          Plane

我想根据国家/地区的所有事故的总和值制作另一个数据框。我们将忽略事故的类型,同时根据国家/地区汇总它们。

我想要的数据框看起来像这样

  Country    |    Sum of Accidents
  England              3
    USA                3
  Germany              1
  Thailand             1

【问题讨论】:

    标签: python pandas


    【解决方案1】:

    选项 1
    使用value_counts

    df.Country.value_counts().reset_index(name='Sum of Accidents')
    

    选项 2
    使用groupby 然后size

    df.groupby('Country').size().sort_values(ascending=False) \
      .reset_index(name='Sum of Accidents')
    

    【讨论】:

      【解决方案2】:

      您可以使用groupby 方法。

      示例 -

      In [36]: df.groupby(["country"]).count().sort_values(["accident"], ascending=False).rename(columns={"accident" : "Sum of accidents"}).reset_index()
      Out[36]:
          country  Sum of accidents
      0   England                 3
      1       USA                 3
      2   Germany                 1
      3  Thailand                 1
      

      解释——

      df.groupby(["country"]).                               # Group by country
          count().                                           # Aggregation function which counts the number of occurences of country
          sort_values(                                       # Sorting it 
              ["accident"],                                  
              ascending=False).        
          rename(columns={"accident" : "Sum of accidents"}). # Renaming the columns
          reset_index()                                      # Resetting the index, it takes the country as the index if you don't do this.
      

      【讨论】:

        猜你喜欢
        • 2021-04-12
        • 2022-01-04
        • 2022-06-16
        • 2019-07-23
        • 2021-09-09
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多