我在其他语言(例如 R 或 SQL)中找到了此选项,但我不太确定如何在 Pandas 中执行此操作。
所以我有一个包含 1262 列和 1 行的文件,每次出现特定值时都需要返回列标题。
例如这个测试数据框:
Date col1 col2 col3 col4 col5 col6 col7
01/01/2016 00:00 37.04 36.57 35.77 37.56 36.79 35.90 38.15
我需要找到列名称,例如其中值 = 38.15。这样做的最佳方式是什么?
谢谢
最佳答案
既然你只有一行,那么你可以对结果调用 iloc[0]
并使用它来屏蔽列:
In [47]:
df.columns[(df == 38.15).iloc[0]]
Out[47]:
Index(['col7'], dtype='object')
分解以上内容:
In [48]:
df == 38.15
Out[48]:
Date col1 col2 col3 col4 col5 col6 col7
01/01/2016 False False False False False False False True
In [49]:
(df == 38.15).iloc[0]
Out[49]:
Date False
col1 False
col2 False
col3 False
col4 False
col5 False
col6 False
col7 True
Name: 01/01/2016, dtype: bool
您还可以使用 idxmax
参数 axis=1
:
In [52]:
(df == 38.15).idxmax(axis=1)[0]
Out[52]:
'col7'
关于python - 返回 pandas 数据框中特定值的列名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38331568/