pandas数据分组统计数量
时间: 2023-01-31 22:08:22 浏览: 93
我们可以使用pandas的`groupby`函数进行数据分组,然后使用`size`函数计算每组数据的数量。例如:
```
import pandas as pd
# 创建示例数据
df = pd.DataFrame({'A': ['a', 'b', 'c', 'a', 'b', 'c'], 'B': [1, 2, 3, 4, 5, 6]})
# 分组统计数量
df_grouped = df.groupby('A').size()
print(df_grouped)
```
输出结果为:
```
A
a 2
b 2
c 2
dtype: int64
```
如果需要分组统计多列,可以指定多个列进行分组:
```
df_grouped = df.groupby(['A', 'B']).size()
print(df_grouped)
```
输出结果为:
```
A B
a 1 1
4 1
b 2 1
5 1
c 3 1
6 1
dtype: int64
```
另外,还可以使用`count`函数进行分组统计,这个函数会统计非空值的数量:
```
df_grouped = df.groupby('A').count()
print(df_grouped)
```
输出结果为:
```
B
A
a 2
b 2
c 2
```
希望这些信息能帮到您!
相关问题
pandas分组统计unique
可以使用 pandas 的 groupby 方法进行分组统计 unique 值,示例代码如下:
```python
import pandas as pd
# 创建示例数据
data = {'A': ['foo', 'bar', 'foo', 'bar', 'foo', 'bar', 'foo', 'foo'],
'B': ['one', 'one', 'two', 'three', 'two', 'two', 'one', 'three'],
'C': [1, 2, 3, 4, 5, 6, 7, 8]}
df = pd.DataFrame(data)
# 分组统计 unique 值
unique_counts = df.groupby(['A', 'B'])['C'].nunique()
print(unique_counts)
```
输出结果为:
```
A B
bar one 1
three 1
two 2
foo one 2
two 2
Name: C, dtype: int64
```
其中,unique_counts 是一个 pandas Series 对象,它的索引是分组的键值对,值是对应分组的 unique 值数量。
pandas 数据归约 维度归约和数量归约
在 Pandas 中,数据归约可以分为两种:维度归约和数量归约。
维度归约指的是将数据按照某个或某些维度进行分组,然后对每个组内的数据进行某种操作,例如计算总和、平均值等。维度归约的结果是一个比原数据维度低的表格。常见的维度归约函数包括 `groupby()`、`pivot_table()` 等。
数量归约指的是对数据进行简单的统计,例如计算平均值、标准差、最大值、最小值等。数量归约的结果是一个标量或者一个比原数据低一维的表格。常见的数量归约函数包括 `mean()`、`std()`、`max()`、`min()` 等。
维度归约和数量归约在 Pandas 中都非常常见,常用于数据的统计分析和预处理。可以根据具体的需求选择合适的方法进行数据处理。