请帮助我解决以下问题:
样本文件:
我尝试汇总6个月的总和,从特定开始日期起每行。
总金额应显示在新列中(自开始日期起6个月之和)
我首先想到的是使用以下代码来获取它:
df['sum_6_months'] = df.loc[:,'01.2018':'06.2018'].apply(sum, axis=1)
但是此代码不是单独,仅适用于所有行的时间范围(01.18-06.18)。
df = pd.DataFrame(np.array([[1, 5, 3, 4, 5, 6, 7, 7, 8,2,5,7,3,4,1], [1, 5, 3, 4, 5, 6, 7, 7,8,2,5,7,3,4,2],[1,5,3, 3, 4, 5, 6, 7, 7, 8,2,5,7,3,4],
[1, 5, 3, 4, 5, 6, 7, 7, 8,2,5,7,3,4,3], [1, 5, 3, 4, 5, 6, 7, 7,8,2,5,7,3,4,4],[1,5,5, 3, 4, 5, 6, 7, 7, 8,2,5,7,3,4],
[1, 5, 3, 4, 5, 6, 7, 7, 8,2,5,7,3,4,5], [1, 5, 3, 4, 5, 6, 7, 7,8,2,5,7,3,4,5],[1,5,2, 3, 4, 5, 6, 7, 7, 8,2,5,7,3,4],
[1, 5, 3, 4, 5, 6, 7, 7, 8,2,5,7,3,4,6], [1, 5, 3, 4, 5, 6, 7, 7,8,2,5,7,3,4,2],[1,5,5, 3, 4, 5, 6, 7, 7, 8,2,5,7,3,4],
[1, 5, 3, 4, 5, 6, 7, 7, 8,2,5,7,3,4,4], [1, 5, 3, 4, 5, 6, 7, 7,8,2,5,7,3,4,2],[1,5,1, 3, 4, 5, 6, 7, 7, 8,2,5,7,3,4]]),
columns=['01.2018', '02.2018', '03.2018', '04.2018', '05.2018','06.2018', '07.2018', '08.2018',
'09.2018','10.2018', '11.2018', '12.2018','01.2019', '02.2019', '03.2019'])
date = [01.2018, 03.2018,04.2018,05.2018,03.2018,01.2018, 03.2018,04.2018,05.2018,03.2018,01.2018, 03.2018,04.2018,05.2018,03.2018]
df['Startdate']= date
答案 0 :(得分:1)
首先,计算每行要跳过的列数:
df2['StartCol'] = 1 + df2.columns[1:].searchsorted(df2.Startdate)
1:
跳过Startdate
列。然后将那么多列“滚动”到左侧,以便它们环绕起来并在每行的末尾结束,取前6个,然后求和:
np.roll(df2.iloc[:, 1:], -df2.StartCol)[:,:6].sum(1)
那给你:
[27, 28, 27, 21, 26, 27, 29, 27, 21, 25, 27, 25, 25, 18, 23]
如果愿意,可以将其存储在新列中。
答案 1 :(得分:1)
df['Startdate']=df['Startdate'].astype(str).str.rjust(7,'0')
df_columns = df.columns.tolist()
def get_sum_six(df_list):
start_date_index = df_columns.index(df_list[-1])
df_list = df_list[0:-1]
sum_of_six = sum(df_list[start_date_index: start_date_index + min(len(df_list)-start_date_index, 6)])
return (sum_of_six)
df['sum_last_six'] = df.apply(lambda x: get_sum_six(x.tolist()), axis=1)