Pandas:仅对最大值求和 DataFrame 列

Pandas: sum DataFrame column for max value only

我有以下数据框:

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 由多少 行最大值 值决定该列包含。

例如,列 b 仅在第 1 行有一个行最大值,因此它的总和是该列中前 1 个最大值的总和,即 0.5 -- 但是列 c 有三个行最大值,分别位于第 1、2 和 4 行,因此应该对列 c 的前 3 个最大值求和。

预期输出:

          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

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.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

最快的方法是使用传递轴参数的 .max() 方法:

df.max(axis =1)

如果你在看另一列:

df['column_name'] = df.max(axis =1)

我没看懂题目!