Pandas: Count city wise number of people from a given of data set (city, name of the person)
Pandas: DataFrame Exercise-28 with Solution
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
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.
Python: Tips of the Day
Walrus Operator:
>>> a = ['j', 'a', 'k', 'd', 'c'] >>> if (n := len(a))%2 == 1: ... print(f'The number of letters is {n}, which is odd.') ... The number of letters is 5, which is odd.
- Exercises: Weekly Top 12 Most Popular Topics
- Pandas DataFrame: Exercises, Practice, Solution
- Conversion Tools
- JavaScript: HTML Form Validation
- SQL Exercises, Practice, Solution - SUBQUERIES
- C Programming Exercises, Practice, Solution : For Loop
- Python Exercises, Practice, Solution
- Python Data Type: List - Exercises, Practice, Solution
- C++ Basic: Exercises, Practice, Solution
- SQL Exercises, Practice, Solution - exercises on Employee Database
- SQL Exercises, Practice, Solution - exercises on Movie Database
- SQL Exercises, Practice, Solution - exercises on Soccer Database
- C Programming Exercises, Practice, Solution : Recursion