the reference answer GPT ᴼ ᴾ ᴱ ᴺ ᴬ ᴵ < br / > you can use np in after the groupby agg. The where condition function to for eligible to sum the data, Here is a sample code:
import numpy as np
# 假设你的数据框名为 df
index_list = list(df.columns[2:]) # 获取所有的指标列名
# 根据 Group 和 Year 进行分组
grouped = df.groupby(['Group', 'Year'])
# 对每组进行条件求和
for group_name, group_df in grouped:
# 按照你的条件进行求和,下面是以 2015 年为例
sum_index1 = np.sum(np.where(group_df['Year'] <= 2015, group_df['Index1'], 0))
sum_index2 = np.sum(np.where(group_df['Year'] <= 2015, group_df['Index2'], 0))
# 其他指标也可以按照相同的方式求和,这里只是示例
print(f"Group: {group_name[0]}, Year: {group_name[1]}, Sum of Index1 before 2015: {sum_index1}, Sum of Index2 before 2015: {sum_index2}")
You can sum indices for other years in a similar way, just by modifying the condition in np.where.