根据另一列计算值的出现次数 [英] Count the number of Occurrence of Values based on another column

查看:72
本文介绍了根据另一列计算值的出现次数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a question regarding creating pandas dataframe according to the sum of other column.

例如,我有这个数据框

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

我想根据国家/地区的所有事故的总和得出另一个数据框.我们将不理会事故的类型,而将所有事故都归因于国家/地区.

I want to make another dataframe based on the sum value of all accident based on the country. We will disregard the type of the accident, while summing them all based on the country.

我的愿望数据框看起来像这样

My desire dataframe would look like this

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

推荐答案

选项1
使用value_counts

Option 1
Use value_counts

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

选项2
使用groupby然后使用size

Option 2
Use groupby then size

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

这篇关于根据另一列计算值的出现次数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆