在 Python Pandas 中计算每个组的唯一值
pythonserver side programmingprogramming更新于 2025/10/27 15:40:17
要在 Python Pandas 中计算每个组的唯一值,我们可以使用 df.groupby('column_name').count()。
步骤
- 创建一个二维、大小可变、可能异构的表格数据 df。
- 打印输入 DataFrame,df。
- 使用 df.groupby('rank')['id'].count() 查找每个组的唯一值的数量并将其存储在变量"count"中。
- 打印步骤 3 中的计数。
示例
import pandas as pd
df = pd.DataFrame(
{
"id": [1, 2, 1, 3, 5, 1, 4, 3, 6, 7],
'rank': [1, 4, 1, 2, 1, 4, 6, 1, 5, 3]
}
)
print"Input DataFrame 1 is:\n", df
count = df.groupby('rank')['id'].count()
print"Frequency of ranks:\n", count
输出
Input DataFrame 1 is: id rank 0 1 1 1 2 4 2 1 1 3 3 2 4 5 1 5 1 4 6 4 6 7 3 1 8 6 5 9 7 3 Frequency of ranks: rank 1 4 2 1 3 1 4 2 5 1 6 1 Name: id, dtype: int64
相关文章
有用资源
python 参考教程 - 该教程包含有关 python 的更多信息:https://www.cainiaomax.com/python/

