我想在每一行中找到最高的值,并在python中返回该值的列标题。例如,我想在每一行中找到前两个:
df =
A B C D
5 9 8 2
4 1 2 3
我希望我的输出看起来像这样:
df =
B C
A D
您可以使用字典理解来生成largest_n
数据帧每一行中的值。我转置了数据框,然后将其应用于nlargest
每个列。我曾经.index.tolist()
提取所需的top_n
列。最后,我将结果转换为所需的数据框形状。
top_n = 2
>>> pd.DataFrame({n: df.T[col].nlargest(top_n).index.tolist()
for n, col in enumerate(df.T)}).T
0 1
0 B C
1 A D
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句