[英]How to add one column according to the order after `groupby` in pandas?
[英]How to multiply rows of one column after groupby in pandas?
我有以下格式的熊貓數據框:
user percent
x 0.2
x 0.5
x 0.8
y 0.1
y 0.6
y 0.2
y 0.6
我試圖乘以每個用戶的行中的百分比。
在此示例中,x的結果將為0.2 * 0.5 * 0.8 = 0.08
因此,數據框應如下所示:
user result
x 0.08
y 0.0072
如何獲得我的預期輸出?
groupby
+ prod
。
df.groupby('user', as_index=False).prod()
user percent
0 x 0.0800
1 y 0.0072
或者,使用apply
+ np.prod
df.groupby('user', as_index=False).apply(np.prod)
user percent
0 x 0.0800
1 y 0.0072
cumprod
+ iloc[-1]
df.groupby('user').percent.apply(lambda x : x.cumprod().iloc[-1])
Out[532]:
user
x 0.0800
y 0.0072
Name: percent, dtype: float64
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.