[英]repeat previous row's value then sum if new values are seen from the same row of another column, then repeat current row in Python
Please see the above link for picture, it will be much easier to understand my question once you saw that picture.请看上面的图片链接,一旦你看到那张图片就会更容易理解我的问题。 sorry I cannot directly post pic in this box.
抱歉,我不能直接在此框中张贴图片。
from Column DI want to create a Column E like in the picture.从 DI 列想要创建一个 E 列,如图所示。 I have spent some hours but could not figure it out.
我已经花了几个小时,但无法弄清楚。 thanks
谢谢
Assuming you can read the data from the excel into a dataframe (df) using read_csv or read_excel, this is what you can do:假设您可以使用 read_csv 或 read_excel 将 excel 中的数据读取到 dataframe (df) 中,您可以执行以下操作:
df['Expected'] = df.groupby('ID')['Amt'].cumsum()
This is how I tested it (ignored the onboard_mth column as it was not needed for testing):这就是我测试它的方式(忽略 onboard_mth 列,因为它不需要测试):
'''
yyyy-mm ID Amt
2019-08 0 0
2019-09 0 0
2019-10 0 0
2019-11 0 0
2019-12 0 0
2020-01 0 0
2020-02 0 0
2020-03 0 100
2020-04 0 0
2020-05 0 0
2020-06 0 0
2020-07 0 0
2020-08 0 150
2020-09 0 0
2020-10 0 0
2020-11 0 0
2020-12 0 1000
2021-01 0 10000
2021-02 0 0
2021-03 0 0
2021-04 0 0
2021-05 0 0
2021-06 0 0
2021-07 0 0
2019-01 1 0
2019-02 1 0
2019-03 1 0
2019-04 1 0
2019-05 1 0
2019-06 1 0
'''
import pandas as pd
df = pd.read_clipboard()
df['Expected'] = df.groupby('ID')['Amt'].cumsum()
print(df)
Output: Output:
yyyy-mm ID Amt Expected
0 2019-08 0 0 0
1 2019-09 0 0 0
2 2019-10 0 0 0
3 2019-11 0 0 0
4 2019-12 0 0 0
5 2020-01 0 0 0
6 2020-02 0 0 0
7 2020-03 0 100 100
8 2020-04 0 0 100
9 2020-05 0 0 100
10 2020-06 0 0 100
11 2020-07 0 0 100
12 2020-08 0 150 250
13 2020-09 0 0 250
14 2020-10 0 0 250
15 2020-11 0 0 250
16 2020-12 0 1000 1250
17 2021-01 0 10000 11250
18 2021-02 0 0 11250
19 2021-03 0 0 11250
20 2021-04 0 0 11250
21 2021-05 0 0 11250
22 2021-06 0 0 11250
23 2021-07 0 0 11250
24 2019-01 1 0 0
25 2019-02 1 0 0
26 2019-03 1 0 0
27 2019-04 1 0 0
28 2019-05 1 0 0
29 2019-06 1 0 0
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.