grouped.count()与筛选配合使用
时间: 2024-05-07 09:19:54 浏览: 19
grouped.count()是用于对某一列数据进行分组统计计数的函数。通常情况下,我们会结合筛选操作来使用它。
比如,我们有一个数据表格,其中有一个“性别”列和一个“年龄”列,我们希望统计不同性别的人数,并且只考虑年龄大于等于18岁的人。那么可以这样做:
```python
import pandas as pd
# 读取数据
data = pd.read_csv('data.csv')
# 筛选出年龄大于等于18岁的数据
data = data[data['年龄'] >= 18]
# 对性别进行分组统计计数
grouped = data.groupby('性别')
count = grouped.count()
print(count)
```
输出结果如下:
```
年龄
性别
女 30
男 40
```
这样,我们就得到了不同性别的人数统计结果。其中,grouped.count()函数返回的是一个新的DataFrame对象,它的行索引是原数据中不同的性别,列索引是原数据中被计数的列(这里是“年龄”),值是计数结果。
相关问题
grouped.count()
`grouped.count()` is a method used in pandas library to count the number of non-null values in each group of a DataFrame. It returns a new DataFrame containing the count of non-null values for each group. Here's an example:
```python
import pandas as pd
# create a sample DataFrame
df = pd.DataFrame({
'group': ['A', 'A', 'B', 'B', 'B'],
'value': [1, 2, 3, 4, 5]
})
# group by 'group' column and get the count of non-null values in each group
grouped = df.groupby('group')
counted = grouped.count()
print(counted)
```
Output:
```
value
group
A 2
B 3
```
In this example, we grouped the DataFrame by the 'group' column and counted the number of non-null values in each group using `grouped.count()`. The output shows that group 'A' has 2 non-null values and group 'B' has 3 non-null values.
grouped.index
grouped.index 是一个 pandas 数据库中的属性,它返回已分组的数据集的索引。这个属性通常在使用 groupby 操作后用于获取每个组的索引。例如,如果我们有一个包含学生姓名、性别和成绩的数据集,我们可以按性别对数据进行分组,然后使用 grouped.index 来获取每个性别的学生姓名。这将返回一个 MultiIndex 对象,其中每个级别都对应于一个分组变量。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)