Niche.P Niche.P - 6 months ago 37
Python Question

Count the number of Occurrence of Values based on another column

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

For example, I have this dataframe

Country | Accident
England Car
England Car
England 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
Germany 1
Thailand 1


Option 1
Use value_counts

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

enter image description here

Option 2
Use groupby then size

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

enter image description here