亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

pandas - 添加聚合功能

pandas - 添加聚合功能

一只名叫tom的貓 2023-10-11 16:01:48
我在 pandas 中有這個數據框:   day customer  amount0    1    cust1     5001    2    cust2     1002    1    cust1      503    2    cust1     1004    2    cust2     2505    6    cust1      20我想創建一個新列“amount2days”,以便匯總過去兩天每個客戶的金額,以獲得以下數據框:   day customer  amount    amount2days   ----------------------------0    1    cust1     500    500           (no past transactions)1    2    cust2     100    100           (no past transactions)2    1    cust1      50    550           (500 + 50 = rows 0,2 3    2    cust1     100    650           (500 + 50 + 100, rows 0,2,3)4    2    cust2     250    350           (100 + 250, rows 1,4) 5    6    cust1      20    20            (notice day is 6, and no day=5 for cust1)即我想執行以下(偽)代碼:df['amount2days'] = df_of_past_2_days['amount'].sum()對于每一行。最方便的方法是什么?我希望在一天內執行求和,但天數不一定必須在每個新行中增加,如示例所示。我仍然想總結過去兩天的金額。
查看完整描述

1 回答

?
呼如林

TA貢獻1798條經驗 獲得超3個贊

我認為這只是幾天的滾動:


def get_roll(x):

    s = pd.Series(x['amount'].values, 

                  index=pd.to_datetime('1900-01-01') + pd.to_timedelta(x['day'], unit='D')

                 )

    return pd.Series(s.rolling('2D').sum().values, index=x.index)


df['amount2days'] = (df.groupby('customer').apply(get_roll)

                       .reset_index(level=0, drop=True)

                    )

輸出:


   day customer  amount  amount2days

1    1    cust1     500        500.0

2    1    cust2     100        100.0

3    1    cust1      50        550.0

4    2    cust1     100        650.0

5    2    cust2     250        350.0

6    3    cust1      20        120.0

選項 2:由于您只想計算兩天的累計金額,因此今天的金額僅加上前一天的金額。所以我們可以利用shift:


df['amount2days'] = df.groupby(['customer','day'])['amount'].cumsum()


# shift the last item of the previous day and add

df['amount2days'] += (df.drop_duplicates(['day','customer'],keep='last')

   .groupby(['customer'])['amount2days'].shift()

   .reindex(df.index)

   .ffill()

   .fillna(0)

)


查看完整回答
反對 回復 2023-10-11
  • 1 回答
  • 0 關注
  • 100 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號