[英]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
請看上面的圖片鏈接,一旦你看到那張圖片就會更容易理解我的問題。 抱歉,我不能直接在此框中張貼圖片。
從 DI 列想要創建一個 E 列,如圖所示。 我已經花了幾個小時,但無法弄清楚。 謝謝
假設您可以使用 read_csv 或 read_excel 將 excel 中的數據讀取到 dataframe (df) 中,您可以執行以下操作:
df['Expected'] = df.groupby('ID')['Amt'].cumsum()
這就是我測試它的方式(忽略 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:
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.