w3resource

Pandas: Count city wise number of people from a given of data set (city, name of the person)


28. City Wise Count

Write a Pandas program to count city wise number of people from a given of data set (city, name of the person).
Sample data:
city Number of people
0 California 4
1 Georgia 2
2 Los Angeles 4

Sample Solution :

Python Code :

import pandas as pd
df1 = pd.DataFrame({'name': ['Anastasia', 'Dima', 'Katherine', 'James', 'Emily', 'Michael', 'Matthew', 'Laura', 'Kevin', 'Jonas'],
'city': ['California', 'Los Angeles', 'California', 'California', 'California', 'Los Angeles', 'Los Angeles', 'Georgia', 'Georgia', 'Los Angeles']})
g1 = df1.groupby(["city"]).size().reset_index(name='Number of people')
print(g1)

Sample Output:

          city  Number of people
0   California                 4
1      Georgia                 2
2  Los Angeles                 4                  

Explanation:

In the above code -

  • Creates a Pandas DataFrame called df1 with two columns, "name" and "city", and 10 rows of data.
  • Groups the rows of df1 by the "city" column using the groupby() method.
  • Applies the size() method to each group to count the number of rows in each group.
  • Resets the index of the resulting DataFrame using the reset_index() method and renames the column with the count as "Number of people".
  • Stores the resulting DataFrame in a variable called g1.
  • The resulting DataFrame has two columns: "city" and "Number of people".
  • Prints the contents of g1 to the console.

For more Practice: Solve these Related Problems:

  • Write a Pandas program to group a DataFrame by city and count the number of unique persons in each group.
  • Write a Pandas program to compute the city-wise count and then sort the results in descending order of count.
  • Write a Pandas program to create a pivot table that summarizes the number of people per city and displays it.
  • Write a Pandas program to merge two DataFrames on city and then compute the overall count of people per city.

Python-Pandas Code Editor:

Have another way to solve this solution? Contribute your code (and comments) through Disqus.

Previous: Write a Pandas program to write a DataFrame to CSV file using tab separator.
Next: Write a Pandas program to delete DataFrame row(s) based on given column value.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.