如果行值大于列的平均值(或中值),那么如何打印列标题。 。查找值大于列平均值的列
对于例如, 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.
如果行值大于列的平均值(或中值),那么如何打印列标题。 。查找值大于列平均值的列
对于例如, 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
使用df.apply
生成一个面罩,然后你就可以遍历和索引df.columns
:
mask = df.apply(lambda x: x > x.mean())
out = [(i, ', '.join(df.columns[x])) for i, x in mask.iterrows()]
print(out)
[(0, 'a, c, d'), (1, 'b, c'), (2, 'd')]
您可以通过使用pandas
试试这个,我打破了步骤
df=df.reset_index().melt('index')
df['MEAN']=df.groupby('variable')['value'].transform('mean')
df[df.value>df.MEAN].groupby('index').variable.apply(list)
Out[1016]:
index
0 [a, c, d]
1 [b, c]
2 [d]
Name: variable, dtype: object
d = defaultdict(list)
v = df.values
[d[df.index[r]].append(df.columns[c])
for r, c in zip(*np.where(v > v.mean(0)))];
dict(d)
{0: ['a', 'c', 'd'], 1: ['b', 'c'], 2: ['d']}
能否请你确认它是什么,你_actually_什么?你想要一个数据框的值还是只是一个简单的元组列表,你需要什么? –
带列标题的元组简单列表。感谢您澄清它。 – Ram
在这种情况下,您接受的答案会给您另外的答案。你能再看一遍吗? –