Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Finding elements in a pandas dataframe

I have a pandas dataframe which looks like the following:

0 1
0 2
2 3
1 4

What I want to do is the following: if I get 2 as input my code is supposed to search for 2 in the dataframe and when it finds it returns the value of the other column. In the above example my code would return 0 and 3. I know that I can simply look at each row and check if any of the elements is equal to 2 but I was wondering if there is one-liner for such a problem.

UPDATE: None of the columns are index columns.

Thanks

like image 654
ahajib Avatar asked Mar 14 '17 20:03

ahajib


People also ask

How do you find things in pandas?

Pandas str. find() method is used to search a substring in each string present in a series. If the string is found, it returns the lowest index of its occurrence. If string is not found, it will return -1.

How do you access individual elements of a Pandas DataFrame?

Learn how to access an element in a Pandas Dataframe using the iat and at functions. Using the Pandas library in Python, you can access elements, a single row or column, or access multiple elements, rows and columns and visualize them. Let's see how. Then we apply at[“Grades”] to this Panda.


2 Answers

>>> df = pd.DataFrame({'A': [0, 0, 2, 1], 'B': [1,2,3,4]})
>>> df
   A  B
0  0  1
1  0  2
2  2  3
3  1  4

The following pandas syntax is equivalent to the SQL SELECT B FROM df WHERE A = 2

>>> df[df['A'] == 2]['B']
2    3
Name: B, dtype: int64

There's also pandas.DataFrame.query:

>>> df.query('A == 2')['B']
2    3
Name: B, dtype: int64
like image 189
blacksite Avatar answered Oct 19 '22 19:10

blacksite


You may need this:

n_input = 2

df[(df == n_input).any(1)].stack()[lambda x: x != n_input].unique()
# array([0, 3])
like image 34
Psidom Avatar answered Oct 19 '22 19:10

Psidom