Skip to main content
 首页 » 编程设计

python之查找值大于列平均值的列

2025年05月04日13lexus

如果行值大于列的平均值(或中值),如何打印列标题。

例如, df = A B C D 0 12 11 13 45 1 6 13 12 23 2 5 12 6 35

the output should be 0: a, c, d. 1: a, b, c. 2: b. 

请您参考如下方法:

In [22]: df.gt(df.mean()).T.agg(lambda x: df.columns[x].tolist()) 
Out[22]: 
0    [a, c, d] 
1       [b, c] 
2          [d] 
dtype: object 

或:

In [23]: df.gt(df.mean()).T.agg(lambda x: ', '.join(df.columns[x])) 
Out[23]: 
0    a, c, d 
1       b, c 
2          d 
dtype: object