Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
146 views
in Technique[技术] by (71.8m points)

python - Return the column name(s) for a specific value in a pandas dataframe

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.

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 

And I need to locate the column name for e.g. where value = 38.15. What is the best way of doing so?

Thanks

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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')

Breaking down the above:

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

You can also use idxmax with param axis=1:

In [52]:
(df == 38.15).idxmax(axis=1)[0]

Out[52]:
'col7'

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...