Search code examples
pythonpandaspandas-locpython-applymap

How to locate the Occurrences of a Specific value in pandas Dataframe


I want to locate a specific value which can occur in multiple columns . In my case it's "False" . I know how to search "False" in individual columns as

df.loc[df['column1']==False]
df.loc[df['column2']==False]

Is there a way to find all at once ?

Unnamed: 0  Incident ID CR Number   Victims Zip Code    Address Number  Latitude    Longitude   Year    Month   Day
0   False   False   True    True    True    True    True    True    True    True    True
1   False   True    False   False   True    True    True    True    True    True    True
2   True    True    True    True    True    True    False   True    True    True    True
3   True    True    False   True    True    True    True    True    True    True    True
4   True    True    True    True    True    True    True    True    False   True    True

I want to see their locations .Hopefully something like

df.applymap.loc(False)

Solution

  • If you want to get the indices stack, then slice:

    s = df.stack()
    s[s.eq(False)].index
    

    Or if you only have True/False:

    s[~s].index
    

    In one line:

    df.stack().loc[lambda s: ~s].index
    

    If you want to assign value(s) on the False positions, a simple boolean indexing will do:

    df[df.eq(False)] = 'X'`
    
    # or, if only True/False in the df 
    df[~df] = 'X'`