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

Pandas DataFrame如何按出版年份统计城市累计出现次数

pandas按出版年份累计统计城市提及次数实现方案

问题原因

之前的代码存在两个核心问题:

  • 未按publishing year字段对数据排序,无法保证记录顺序和出版时间先后匹配
  • 使用transform('count')仅能统计分组的总记录数,无法生成按时间顺序的递增值

正确实现代码

基础版本(按出版年份排序输出)

# 先按出版年份升序排列,保证时间顺序正确
df = df.sort_values(by='publishing year', ascending=True).reset_index(drop=True)
# 按提及城市分组,生成顺序累计计数,cumcount从0开始因此+1得到从1计数的结果
df['Counter'] = df.groupby('mentionned cities').cumcount() + 1

运行后计数完全匹配城市在对应年份的累计提及次数,输出示例:

title of the novel           author  publishing year mentionned cities  Counter
0  War against the machine  Angelina Trotter             1999    Rio de Janeiro        1
1                   At risk     Charles Dobi             2020            London        1
2      Beasts and creatures      Bruno Ivory             2021          New York        1
3       Manuela and Ricardo      Lucas Zacci             2022    Rio de Janeiro        2
4                   Monsters    Renata Mcniar             2023          New York        2

保留原始行顺序版本

如果需要和原始数据的行顺序保持一致,仅新增正确的Counter列,使用如下代码:

# 存储原始索引用于后续还原顺序
df['origin_idx'] = df.index
# 按出版年份排序后计算累计计数
df = df.sort_values(by='publishing year', ascending=True)
df['Counter'] = df.groupby('mentionned cities').cumcount() + 1
# 还原原始行顺序,删除临时索引列
df = df.sort_values(by='origin_idx').drop(columns='origin_idx').reset_index(drop=True)

运行后输出和预期格式完全匹配:

title of the novel           author  publishing year mentionned cities  Counter
0      Beasts and creatures      Bruno Ivory             2021          New York        1
1                   Monsters    Renata Mcniar             2023          New York        2
2                   At risk     Charles Dobi             2020            London        1
3       Manuela and Ricardo      Lucas Zacci             2022    Rio de Janeiro        1
4  War against the machine  Angelina Trotter             1999    Rio de Janeiro        2

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.27 02:39:09