You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何统计Pandas DataFrame中ID的出现次数并生成新DataFrame

Pandas统计ID出现次数的解决方案

原DataFrame

IDtimeother
081219blue
032323green
1423red
14232blue
142424red
242422blue

需求

统计每个ID的出现次数,生成如下结构的新DataFrame:

IDnumber_appears
02
13
21

实现方法

方法1:用value_counts()快速统计

这是最直观的方式,直接对ID列统计频次,再调整格式:

import pandas as pd

# 构造原数据
df = pd.DataFrame({
    'ID': [0, 0, 1, 1, 1, 2],
    'time': [81219, 32323, 423, 4232, 42424, 42422],
    'other': ['blue', 'green', 'red', 'blue', 'red', 'blue']
})

# 统计ID频次并调整列名和顺序
result = df['ID'].value_counts().reset_index()
result.columns = ['ID', 'number_appears']
result = result.sort_values('ID').reset_index(drop=True)

print(result)

方法2:groupby() + size()分组统计

通过分组ID后计算每组行数,直接得到有序结果:

result = df.groupby('ID').size().reset_index(name='number_appears')
print(result)

方法3:pivot_table()透视表统计

用透视表的方式也能实现同样效果:

result = df.pivot_table(index='ID', aggfunc='size').reset_index(name='number_appears')
print(result)

以上三种方法最终都会输出符合需求的结果。

内容的提问来源于stack exchange,提问作者Carola

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.19 09:05:21