简体   繁体   中英

get column name that contains a specific value in pandas

I want to get column name from the whole database (assume the database contains more than 100 rows with more than 50 column) based on specific value that contain in a specific column in pandas.

Here is my code:

import pandas as pd
df = pd.DataFrame({'A':[1,2,3], 'B':[4,5,6], 'C':[7,8,9]})
pos = 2
response = raw_input("input")
placeholder = (df == response).idxmax(axis=1)[0]
print df
print (placeholder)

Tried a lot . . .

Example: when the user will input 2; it will show answer: A if the input is 4; feedback will be B and if 7 then reply will be C

tried iloc but I've seen row have to be noticed there.

Please Help Dear Guys . . . . . Thanks . . . :)

First of all you should treat the input as integer. So instead of raw_input , use input :

response = input("input")

After that you can use any :

df[df==YOUR_VALUE].any()

This will return a boolean Series with columns names and whether they contain the value you are looking for.

In your example:

df = pd.DataFrame({'A':[1,2,3], 'B':[4,5,6], 'C':[7,8,9]})
response = input("input")
placeholder = df[df==response].any()

for input 4 the output will be:

A    False
B     True
C    False
dtype: bool

Try this

for i in df.columns:
    newDf = df.loc[lambda df: df[i] == response]
    if(not newDf.empty):
        print(i)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM