w3resource

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.



Share this Tutorial / Exercise on : Facebook and Twitter

Python: Tips of the Day

Inserting if statements using conditional list comprehensions:

x = [1, 2, 3, 4, 5, 6]
result = []
for idx in range(len(x)):
    if x[idx] % 2 == 0:
        result.append(x[idx] * 2)
    else:
        result.append(x[idx])
result

Output:

[1, 4, 3, 8, 5, 12]
[(element * 2 if element % 2 == 0 else element) for element in x]

Output:

[1, 4, 3, 8, 5, 12]
[element * 2 for element in x if element % 2 == 0]

Output:

[4, 8, 12]