返回 pandas 数据框中特定值的列名 [英] Return the column name(s) for a specific value in a pandas dataframe
问题描述
我在其他语言(例如R或SQL)中找到了此选项,但是我不太确定如何在Pandas中进行此操作.
where I have found this option in other languages such as R or SQL but I am not quite sure how to go about this in Pandas.
因此,我有一个包含1262列和1行的文件,并且每次出现特定值时都需要返回列标题.
So I have a file with 1262 columns and 1 row and need the column headers to return for every time that a specific value appears.
比如说这个测试数据框:
Say for example this test dataframe:
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.最好的方法是什么?
And I need to locate the column name for e.g. where value = 38.15. What is the best way of doing so?
谢谢
推荐答案
由于您只有一行,因此您可以对结果调用iloc[0]
并使用它来屏蔽列:
Seeing as you only have a single row then you can call iloc[0]
on the result and use this to mask the columns:
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
的a>:
You can also use idxmax
with param axis=1
:
In [52]:
(df == 38.15).idxmax(axis=1)[0]
Out[52]:
'col7'
这篇关于返回 pandas 数据框中特定值的列名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!