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

如何基于同一api_spec_id统计Pandas DataFrame的版本总数

问题描述

我有如下结构的Pandas DataFrame:

api_spec_id       commitdates       commits Year-Month API Age info_version  
84                  2014-12-15      110      2014-12     110      6.0.1  
84                  2014-11-06       33      2014-11      33      6.0.2
84                  2014-10-15      110      2014-10     110      6.0.3
84                  2014-12-02      110      2014-12     110      6.0.5
84                  2014-11-19       33      2014-11      33      7.0.2

其中api_spec_id是每个API的唯一标识,同一ID下的API会随提交日期更新不同版本。我需要为api_spec_id=84的所有行添加Total_versions列,显示该ID对应的总版本数(此处为5),期望输出如下:

api_spec_id       commitdates       commits Year-Month API Age info_version  Total_versions
84                  2014-12-15      110      2014-12     110      6.0.1       5
84                  2014-11-06       33      2014-11      33      6.0.2       5
84                  2014-10-15      110      2014-10     110      6.0.3       5
84                  2014-12-02      110      2014-12     110      6.0.5       5
84                  2014-11-19       33      2014-11      33      7.0.2       5

尝试过value_counts()、sum()等方法,但均未得到预期结果,求可行解决方案。

解决方案

方法1:仅针对单个ID处理

如果只需要给api_spec_id=84的行添加列,直接计算该ID的总行数后赋值即可:

# 计算api_spec_id=84的总版本数
total_count = len(df[df['api_spec_id'] == 84])
# 为对应行添加Total_versions列
df.loc[df['api_spec_id'] == 84, 'Total_versions'] = total_count

方法2:批量处理所有ID

如果需要给每个api_spec_id的行都添加对应总版本数,用groupby结合transform方法自动填充:

# 按api_spec_id分组,每组内计算行数并填充到新列
df['Total_versions'] = df.groupby('api_spec_id')['api_spec_id'].transform('count')

这种方法会自动为每个ID的所有行填充该ID对应的总版本数,适合多ID的批量场景。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.11 15:10:18