沒有 itertuples 我無法解決這個問題
我想從累積加起來小于不同列總和的 1/3 的每一行中取平均值
起始資料幀:
df = pd.DataFrame({'model_1': [0.15, 0.19, 0.25, 0.54, 0.55 , 0.98, 1.12],
'model_2': [0.12, 0.13, 0.32, 0.45, 0.6 , 0.7, 1.05],
'exposure': [0.4, 1, 1.6, 1, 2, 2, 3],
'target': [0.1, 0.2, 0.3, 0.4, 0.5, 0.8, 1.1]})
這里我們看到曝光的總和是11,我的意圖是做3個bucket,取所有累積和小于等于總曝光1/3的行的平均值
所以我們可以看到前 4 行的累積和為 4,然后我想取這些列的相對平均值。
這意味著 aggr_model_1 中的第一個值是:
((0.15 * 0.4) (0.19 * 1) (0.25 * 1.6) 0.54)/4 = 0.2975
然后將相同的程序應用于 aggr_model_2 和 aggr_target
輸出資料幀:
output_df = pd.DataFrame({'aggr_model_1': [0.2975, 0.765, 1.12],
'aggr_model_2': [0.285, 0.65, 1.05],
'aggr_exposure': [4, 4, 3],
'aggr_target': [0.28, 0.65, 1.1]})
uj5u.com熱心網友回復:
我來試一試,看看我是否理解正確。該計算的組成部分是:
- 總曝光量,我們可以計算為
total = df.exposure.sum() - 將總曝光量分成 3 部分的 bins
bins = np.linspace(0, total, 4) - 累積曝光量,即
cum_exposure = df.exposure.cumsum() - 分檔累積暴露
bin_cum_exposure = pd.cut(cum_exposure, bins) - 暴露加權觀察
w_model_1 = df.exposure * df.model_1 - 意思!
df.groupby('bin_cum_exposure').w_model_1.mean()
把東西放在一起:
total = df.exposure.sum()
bins = np.linspace(0, total, 4)
(df.assign(bin_cum_exposure = lambda x: pd.cut(x.exposure.cumsum(), bins),
w_model_1 = lambda x: x.exposure * x.model_1,
w_model_2 = lambda x: x.exposure * x.model_2,
w_total = lambda x: x.exposure * x.target)
.groupby('bin_cum_exposure')
.mean()
)
答案與您的手動計算不同,因為第一個 bin 有 3 個元素,而不是您的示例中的 4 個元素。
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/331196.html
下一篇:如何從輸出中獲取熊貓資料框?
