pandas表聚合后某列去重计数
时间: 2023-10-28 10:51:07 浏览: 44
好的,对于您的问题,可以使用 pandas 中的 groupby 和 nunique 函数来实现该操作。具体来说,假设表格名为 df,某列名为 col,可以使用以下代码实现操作:
df.groupby(['col']).nunique()
这将返回以 col 列为分组依据,统计出每个组内唯一值数量的结果表格。
相关问题
pandas表聚合后某列进行去重计数
Sure, I can help with that! To count the number of unique values in a column after aggregating a Pandas DataFrame, you can use the nunique() method. Here's an example:
```
import pandas as pd
# Create a sample DataFrame
df = pd.DataFrame({
'group': ['A', 'B', 'A', 'B', 'A', 'B'],
'value': [1, 2, 3, 1, 2, 1]
})
# Aggregate the DataFrame by group and count the number of unique values of 'value'
counts = df.groupby('group')['value'].nunique()
print(counts)
```
This will output:
```
group
A 3
B 2
Name: value, dtype: int64
```
I hope that helps!
python groupby agg 根据条件去重计数
在 Python 中,可以使用 `groupby` 函数和 Pandas 库来实现根据条件去重并计数的操作。
假设有一个 Pandas 数据框 `df`,其中包含了多个行,每行都有一个 `id` 和 `category` 属性,我们要对 `category` 属性进行分组,并去重计数。
示例代码如下:
```python
import pandas as pd
df = pd.DataFrame({
'id': [1, 2, 3, 4, 5, 6, 7],
'category': ['A', 'B', 'C', 'A', 'A', 'B', 'C']
})
result = df.groupby('category').agg({'id': 'nunique'})
print(result)
```
输出结果为:
```
id
category
A 3
B 2
C 2
```
解释:首先使用 Pandas 的 `groupby` 函数按 `category` 属性进行分组,然后使用 `agg` 函数对每个分组进行聚合计算。在本例中,我们使用 `nunique` 函数(去重计数)对 `id` 属性进行计算。最后输出计算结果。