Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

See if a value exists in a DataFrame

In Python to check if a value is in a list you can simply do the following:

>>>9 in [1,2,3,6,9]
True

I would like to do the same for a Pandas DataFrame but unfortunately Pandas does not recognise that notation:

>>>import pandas as pd
>>>df = pd.DataFrame([[1,2,3,4],[5,6,7,8]],columns=["a","b","c","d"])
   a  b  c  d
0  1  2  3  4
1  5  6  7  8
>>>7 in df
False

How would I achieve this using Pandas DataFrame without iterating through each column/row or anything complicated?

like image 894
user3374113 Avatar asked Jan 03 '16 06:01

user3374113


People also ask

How do you check if an element is in a series Python?

isin() function check whether values are contained in Series. It returns a boolean Series showing whether each element in the Series matches an element in the passed sequence of values exactly.

How do you check if a string is in a DataFrame Python?

Using “contains” to Find a Substring in a Pandas DataFrame The contains method returns boolean values for the Series with True for if the original Series value contains the substring and False if not. A basic application of contains should look like Series. str. contains("substring") .


1 Answers

Basically you have to check the matrix without the schema, so:

 7 in df.values

x in df checks if x is in the columns:

for x in df:
    print x,

out: a b c d
like image 88
Ezer K Avatar answered Nov 09 '22 11:11

Ezer K