python - 返回 pandas 数据框中特定值的列名

标签 python pandas

我在其他语言(例如 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/

相关文章:

python - HTML 标签之间的 Selenium

python - 如何在单个项目中获取scrapy xpath输出

python - 如何将这个简单的 5 个字节变回 4 个字节? (将 4 个字节转换为 5 个字节的算法是已知的)

python - Gremlin Python - 如何从 valueMap 获取 ID

python - 通过将字典中的值映射到现有列来在数据框中创建新列

python - 如何从 3 类数据帧的前 2 类中删除 1 行?

python - Django 休息框架 : How to enable swagger docs for function based views

python - 如果有多个条件无法弄清楚

python - 根据另一列的排序,使用 pandas GroupBy 连接字符串

python - 奇怪的语法(Python/Pandas)