第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

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

pandas - 添加聚合功能

pandas - 添加聚合功能

一只名叫tom的貓 2023-10-11 16:01:48
我在 pandas 中有這個數(shù)據(jù)框:   day customer  amount0    1    cust1     5001    2    cust2     1002    1    cust1      503    2    cust1     1004    2    cust2     2505    6    cust1      20我想創(chuàng)建一個新列“amount2days”,以便匯總過去兩天每個客戶的金額,以獲得以下數(shù)據(jù)框:   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)即我想執(zhí)行以下(偽)代碼:df['amount2days'] = df_of_past_2_days['amount'].sum()對于每一行。最方便的方法是什么?我希望在一天內(nèi)執(zhí)行求和,但天數(shù)不一定必須在每個新行中增加,如示例所示。我仍然想總結(jié)過去兩天的金額。
查看完整描述

1 回答

?
呼如林

TA貢獻1798條經(jīng)驗 獲得超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 關注
  • 93 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯(lián)系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網(wǎng)微信公眾號