我试图对列中的值求和并在每年的某个月份重置。我已检查了以下有用的链接,但我似乎仍然找不到为我指明正确方向的答案。
Cumulative sum at intervals Reset Cumulative sum base on condition Pandas Conditional count of cumulative sum Dataframe - Loop through columns Pandas: conditional rolling count
与我正在寻找的内容最接近的链接( Pyspark : Cumulative Sum with reset condition ),但我不知道如何将其从 PySpark 转换为 Pandas (或其他 Python 方法)。
raw_data = {'change_value': [-6, -13, -19, -82, -25, -39, -27, 0, 8, 32, 55, 94, 75, 77],
'cumu_value': [-6, -19, -38, -120, -145, -184, -211, -211, -203, -171, -116, -22, 75, 130],
'month': [10, 11, 12, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11],
'date': ['2017-10','2017-11','2017-12','2018-01','2018-02','2018-03'
,'2018-04','2018-05','2018-06','2018-07','2018-08','2018-09',
'2018-10', '2018-11']}
df = pd.DataFrame(raw_data, columns = ['change_value', 'cumu_value', 'month', 'date'])
df
df.loc[df['month'] == '10', ['cumu_value']] = df['change_value']
df['cumu_value'] = df.change_value.cumsum()
change_value cumu_value month date
0 -6 -6 10 2017-10
1 -13 -19 11 2017-11
2 -19 -38 12 2017-12
3 -82 -120 1 2018-01
4 -25 -145 2 2018-02
5 -39 -184 3 2018-03
6 -27 -211 4 2018-04
7 0 -211 5 2018-05
8 8 -203 6 2018-06
9 32 -171 7 2018-07
10 55 -116 8 2018-08
11 94 -22 9 2018-09
12 75 75 10 2018-10 <<<< every October I would like the to cumu_value to reset - to that month's change_value
13 77 130 11 2018-11 <<< for some reason the cumu_value adds all the values for all the months rather than just the value for 2018-10 and 2018-11
最佳答案
创建 group_id 每年 10 月更改的群组
。然后在每个组内cumsum
,每年十月有效地重置它。
df['cumu_value'] = df.groupby(df.month.eq(10).cumsum()).change_value.cumsum()
输出:
change_value cumu_value month date
0 -6 -6 10 2017-10
1 -13 -19 11 2017-11
2 -19 -38 12 2017-12
3 -82 -120 1 2018-01
4 -25 -145 2 2018-02
5 -39 -184 3 2018-03
6 -27 -211 4 2018-04
7 0 -211 5 2018-05
8 8 -203 6 2018-06
9 32 -171 7 2018-07
10 55 -116 8 2018-08
11 94 -22 9 2018-09
12 75 75 10 2018-10
13 77 152 11 2018-11
<小时/>
作为示例,我们将行分组在一起,如下所示:
print(df.month.eq(10).cumsum())
0 1
1 1
2 1
3 1
4 1
5 1
6 1
7 1
8 1
9 1
10 1
11 1
12 2
13 2
Name: month, dtype: int32
因此我们将前 12 行与最后 2 行分开进行求和
。
关于python - Python中列值的累积和循环重置每年特定月份的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53753208/