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

使用Pandas计算每4行季度数据年均值并分配新行标签的方法

你可以直接从季度字段提取年份后,按国家和年份分组求均值即可,完整实现代码如下:

import pandas as pd

# 构造原始DataFrame
d = {'quarter': ['1996q1', '1996q2', '1996q3', '1996q4', '1997q1', '1997q2', '1997q3', '1997q4', '1996q1', '1996q2', '1996q3', '1996q4', '1997q1', '1997q2', '1997q3', '1997q4'], 'country': ['USA', 'USA', 'USA', 'USA', 'USA', 'USA', 'USA', 'USA', 'ITA', 'ITA', 'ITA', 'ITA', 'ITA', 'ITA', 'ITA', 'ITA'], 'value': [0, 0, 0, 0, 1, 1, 1, 1, 3, 3, 5, 0, 0, 0, 2, 2]}
df = pd.DataFrame(data=d)

# 提取季度字符串前4位作为年份
df['year'] = df['quarter'].str[:4]

# 按国家、年份分组计算平均值,保留两位小数
df2 = df.groupby(['country', 'year'], as_index=False)['value'].mean().round(2)

# 调整列顺序匹配预期输出
df2 = df2[['year', 'country', 'value']]

# 如果需要和示例完全一致的排序(USA在前),补充排序逻辑即可
df2 = df2.sort_values(by=['country', 'year'], ascending=[False, True]).reset_index(drop=True)

print(df2)

运行后输出结果:

year country  value
0  1996     USA   0.00
1  1997     USA   1.00
2  1996     ITA   2.75
3  1997     ITA   1.00

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.02 03:30:03