pandas分组统计unique
时间: 2023-05-10 09:55:03 浏览: 77
可以使用 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 groupby 唯一统计
pandas groupby唯一统计是指通过对数据进行分组,然后对每个组中的唯一值进行计数。可以使用groupby()函数将数据按照指定的列进行分组,然后使用nunique()函数对每个组中的唯一值进行计数。下面是一个简单的例子:
```python
import pandas as pd
# 创建一个DataFrame
data = {'Group': ['A', 'A', 'B', 'B', 'B', 'C'],
'Value': [1, 2, 3, 4, 5, 6]}
df = pd.DataFrame(data)
# 使用groupby和nunique统计每个组的唯一值数量
result = df.groupby('Group')['Value'].nunique()
print(result)
```
输出结果为:
```
Group
A 2
B 3
C 1
Name: Value, dtype: int64
```
这里,我们根据'Group'列进行了分组,并对每个组中的'Value'列的唯一值进行了计数。组'A'有2个唯一值,组'B'有3个唯一值,组'C'有1个唯一值。
pandas先分组再统计不同的要素个数
你可以使用`groupby`函数将数据按照某一列分组,然后使用`nunique`函数统计分组后每组中不同要素的个数。
例如,假设有一个数据集`df`,其中有两列`category`和`item`,你想要按照`category`列进行分组,统计每组中不同的`item`个数,可以使用以下代码:
```python
grouped = df.groupby('category')
result = grouped['item'].nunique()
```
这将返回一个`Series`对象,其中每个索引表示一个分组,对应的值为该分组中不同`item`的个数。