Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python pandas: Getting the locations of a value in dataframe

Suppose I have the following dataframe:

   'a' 'b'
0   0   0
1   1   0
2   0   1
3   0   1

Is there a way I could get the index/column values for which a specific value exists? For example, something akin to the following:

values = df.search(1)

would have values = [(1, 'a'), (2, 'b'), (3, 'b')].

like image 263
hlin117 Avatar asked Mar 11 '15 06:03

hlin117


People also ask

How do you find the location of a value in a DataFrame?

To find the indexes of the specific value that match the given condition in Pandas dataframe we will use df['Subject'] to match the given values and index. values to find an index of matched value. The result shows us that rows 0,1,2 have the value 'Math' in the Subject column.

How do you access individual elements of a DataFrame in Python?

By using loc and iloc We can access a single row and multiple rows of a DataFrame with the help of “loc” and “iloc”. Access a single row or multiple rows by name.

How do you access values in a DataFrame in Python?

You can get the value of a cell from a pandas dataframe using df. iat[0,0] .


1 Answers

df[df == 1].stack().index.tolist()

yields

[(1, 'a'), (2, 'b'), (3, 'b')]
like image 163
Alex Avatar answered Nov 03 '22 01:11

Alex