Python中列值的累积和循环在每个Y的特定月份重置值

2024-04-26 03:06:55 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图在列中求和值,然后在每年的某个月重置。我已经检查了下面的链接,这些链接对我很有帮助,但我似乎还是找不到指向正确方向的答案。在

Cumulative sum at intervalsReset Cumulative sum base on condition PandasConditional count of cumulative sum Dataframe - Loop through columnsPandas: 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

Tags: thetopandasdffordatevalue链接
1条回答
网友
1楼 · 发布于 2024-04-26 03:06:55

创建groups,其中组的id每年10月都会更改。然后在每个组中cumsum,有效地在每年10月重置它。在

df['cumu_value'] = df.groupby(df.month.eq(10).cumsum()).change_value.cumsum()

输出:

^{pr2}$

作为示例,我们将行分组,如下所示:

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

所以我们cumsum前12行与最后2行分开。在

相关问题 更多 >