import numpy as np
import pandas as pd
data = {'experiment_name': ['exp1', 'exp1', 'exp1', 'exp1', 'exp1', 'exp1'],
'variant': ['A', 'B', 'A','B','A','B'],'sessions_with_orders':[1,2,6,0,23,12],
'total_sessions':[10,23,56,22,89,12]}
# Create DataFrame
df = pd.DataFrame(data)
df.pivot_table(index='variant',columns='experiment_name',values=['total_sessions','sessions_with_orders'],aggfunc=np.sum)
我有一些資料框,我使用聚合函式對其進行旋轉。
我得到的輸出是需要的。但是,我想創建 ratio sessions_with_orders/total_sessions。我該怎么做呢?這在 excel 上是可行的,但我無法考慮 pandas-data 框架。
我不了解 lambda、cross_tab 或如何實作它們。
我在 python 上3.9.8。np 版本1.22.3和 pd 版本1.3.4
uj5u.com熱心網友回復:
IIUC,您可以使用assign:
(df
.pivot_table(index='variant',columns='experiment_name',values=['total_sessions','sessions_with_orders'],aggfunc=np.sum)
.assign(ratio=lambda d: d['sessions_with_orders']/d['total_sessions'])
)
輸出:
sessions_with_orders total_sessions ratio
experiment_name exp1 exp1
variant
A 30 155 0.193548
B 14 57 0.245614
但是,如果您有多個實驗,則最好使用join(我在此處將最后一個實驗更改為“exp2”以進行演示):
df2 = df.pivot_table(index='variant',columns='experiment_name',
values=['total_sessions','sessions_with_orders'],
aggfunc=np.sum)
df2.join(pd.concat({'ratio': df2['sessions_with_orders'].div(df2['total_sessions'])},
axis=1))
輸出:
sessions_with_orders total_sessions ratio
experiment_name exp1 exp2 exp1 exp2 exp1 exp2
variant
A 30.0 NaN 155.0 NaN 0.193548 NaN
B 2.0 12.0 45.0 12.0 0.044444 1.0
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/461722.html
