我有以下資料框:
df = pd.DataFrame({'a': [0.28, 0, 0.25, 0.85, 0.1],
'b': [0.5, 0.5, 0, 0.75, 0.1],
'c': [0.33, 0.7, 0.25, 0.2, 0.5],
'd': [0, 0.25, 0.2, 0.66, 0.1]})
輸出:
a b c d
0 0.28 0.50 0.33 0.00
1 0.00 0.50 0.70 0.25
2 0.25 0.00 0.25 0.20
3 0.85 0.75 0.20 0.66
4 0.10 0.10 0.50 0.10
對于每一列,我想對列的最高n最大值求和,其中n由該列包含的行最大值決定。
例如,columnb僅在第 1 行有一個最大行,所以它的總和是該列中前 1 個最大值的總和,這只是0.5- 但 columnc有三個 row-maxes,位于第 1、2 和4,所以列的前 3 個最大值c應該相加。
預期輸出:
a b c d
0 0.28 0.50 0.33 0.00
1 0.00 0.50 0.70 0.25
2 0.25 0.00 0.25 0.20
3 0.85 0.75 0.20 0.66
4 0.10 0.10 0.50 0.10
count 1.10 0.50 1.45 0.00
uj5u.com熱心網友回復:
where
df.append(
df.where( # only look at values that are max for the row
df.eq( # compare max values to all values in row just in case there are more than 1
df.max(axis=1), # actually get max values
axis=0
)
).sum().rename('count')
)
a b c d
0 0.28 0.50 0.33 0.00
1 0.00 0.60 0.50 0.25
2 0.25 0.00 1.00 0.20
3 0.85 0.75 0.20 0.66
4 0.10 0.10 0.50 0.10
count 0.85 1.10 1.50 0.00
uj5u.com熱心網友回復:
最快的方法是使用傳遞軸引數的 .max() 方法:
df.max(axis =1)
如果您在另一列之后:
df['column_name'] = df.max(axis =1)
我沒有很好地閱讀這個問題!
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/451427.html
