python groupby count()
时间: 2023-08-29 12:12:48 浏览: 83
Python中的groupby分组功能的实例代码
The groupby() function in Python is used to group the data based on a specific column. The count() function is used to count the number of occurrences of each group.
Here is an example of how to use groupby() and count() functions in Python:
```python
import pandas as pd
# create a sample dataframe
df = pd.DataFrame({'Name': ['John', 'Mary', 'John', 'Peter', 'Mary'],
'Age': [25, 35, 30, 45, 40],
'City': ['New York', 'Los Angeles', 'Chicago', 'Houston', 'Miami']})
# group by the 'Name' column and count the number of occurrences
count_df = df.groupby(['Name']).count()
print(count_df)
```
Output:
```
Age City
Name
John 2 2
Mary 2 2
Peter 1 1
```
In the above example, we have grouped the data by the 'Name' column and counted the number of occurrences of each name. The resulting dataframe shows the count for each name.
阅读全文