[英]Pandas what is the best way row sum without min & max value
從下面的評估數據中,我想得到每行的總和,除了最小值和最大值。
col_a col_b col_c col_d col_e
P0 1 7 2 5 2
P1 5 2 3 2 5
P2 2 0 1 4 2
預期的:
col_mean
P0 3 # mean(2, 5, 2)
P1 3.33 # mean(2, 3, 5), if there are two max (min) value, except just one
P2 1.66 # mean(2, 1, 2)
得到這個的最好方法是什么?
像這樣的東西應該滿足你的要求。 按升序對它們進行逐行排序,然后取 bd 列的平均值
df.values.sort(1)
df.iloc[:,1:-1].mean(1)
Output
P0 3.000000
P1 3.333333
P2 1.666667
您可以嘗試使用:
df['mean'] = (df.sum(axis=1) - (df.min(axis=1) + df.max(axis=1))) / (df.shape[1]-2)
返回:
col_a col_b col_c col_d col_e mean
0 1 7 2 5 2 3.000000
1 5 2 3 2 5 3.333333
2 2 0 1 4 2 1.666667
另一種方式:
f = lambda x: (x.sum() - x.max() - x.min())/(len(x)-2) if len(x) > 2 else 0
df.apply(f,axis=1)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.