[英]Pandas / Python: Groupby.apply() with function dictionary
[英]Lambda function operations using groupby.apply() in dataframe
我有一個 DataFrame,看起來像這樣:
構建它的代碼是:
data = {'Position Date': ['2022-01-02', '2022-01-02', '2022-01-02', '2022-01-02', '2022-01-03', '2022-01-03', '2022-01-03', '2022-01-03'],
'Client': ['Client 1', 'Client 1', 'Client 2', 'Client 2', 'Client 1', 'Client 1', 'Client 2', 'Client 2'],
'Product': ['Product 1', 'Product 4', 'Product 2', 'Product 3', Product 1', 'Product 4', 'Product 2', 'Product 3'],
'Buy Date': ['2022-05-02', '2022-06-02', '2022-03-12', '2022-01-25', '2022-05-02', '2022-06-02', '2022-03-12', '2022-01-25'],
'Position': [130, 5000, 120, 77, 150, 7000, 200, 100]}
df = pd.DataFrame(data).set_index(['Position Date', 'Client', 'Product', 'Buy Date'])
df['PL'] = df.groupby(level=['Client', 'Product', 'Buy Date']).diff().fillna(0)
所以,現在我需要創建一個新列 X,將“當天”PL(索引 0)除以最后一天 Position(索引 -1)。
例如:在 2022 年 1 月 3 日那天,客戶 1,產品 1 x 將是:
X = PL[索引 0] / 位置 [-1] = 20/ 130
預期的 output 將是:
由於第一天的值為 0,其余為:20/130、2000/5000、80/120、23/77
我正在嘗試類似的東西
df.groupby(level=['Client', 'Product', 'Buy Date']).apply(lambda x: x['PL'] / x['Position'].iloc[-1])
但我不斷收到錯誤。
我會在這里使用索引:
df['output'] = df['PL'].div(df.loc[df.index[0][0], 'Position']
.reindex(df.droplevel('Position Date').index).values
)
Output:
Position PL output
Position Date Client Product Buy Date
2022-01-02 Client 1 Product 1 2022-05-02 130 0.0 0.000000
Product 4 2022-06-02 5000 0.0 0.000000
Client 2 Product 2 2022-03-12 120 0.0 0.000000
Product 3 2022-01-25 77 0.0 0.000000
2022-01-03 Client 1 Product 1 2022-05-02 150 20.0 0.153846
Product 4 2022-06-02 7000 2000.0 0.400000
Client 2 Product 2 2022-03-12 200 80.0 0.666667
Product 3 2022-01-25 100 23.0 0.298701
中間體:
df.loc[df.index[0][0], 'Position']
Client Product Buy Date
Client 1 Product 1 2022-05-02 130
Product 4 2022-06-02 5000
Client 2 Product 2 2022-03-12 120
Product 3 2022-01-25 77
Name: Position, dtype: int64
(df.loc[df.index[0][0], 'Position']
.reindex(df.droplevel('Position Date').index)
)
Client Product Buy Date
Client 1 Product 1 2022-05-02 130
Product 4 2022-06-02 5000
Client 2 Product 2 2022-03-12 120
Product 3 2022-01-25 77
Client 1 Product 1 2022-05-02 130
Product 4 2022-06-02 5000
Client 2 Product 2 2022-03-12 120
Product 3 2022-01-25 77
Name: Position, dtype: int64
(df.loc[df.index[0][0], 'Position']
.reindex(df.droplevel('Position Date').index)
.values
)
array([ 130, 5000, 120, 77, 130, 5000, 120, 77])
df["X"] = df["PL"].div(df["Position"].shift(4)).fillna(0.0).values
其中shift
法中的4是Position Date
列中一天內的產品總數(產品1、產品2、產品3和產品4)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.