Search code examples
pythonpandasdata-analysisdata-cleaning

Search in multiple Columns with isin function in Pandas


I want to search, if my date in one dataframe is existing in one of multiple columns of another dataframe, because here are more than one date columns.

When I want to search in one column I did this:

df = df.assign(InDatum=df.Datum.isin(KBlatt.erdat).astype(int))

Which give me the right solution, but only for one column.

I want to search the values "Datum" in two more columns than "erdat".

I tried to implement it with an or, but it didn't worked out:

df = df[(df.assign(InDatum=df.Datum.isin(KBlatt.erdat).astype(int))) | (df.assign(InDatum=df.Datum.isin(KBlatt.erldat).astype(int))) | (df.assign(InDatum=df.Datum.isin(KBlatt.aendat).astype(int)))]

Solution

  • Just select the target columns and flatten:

    df.assign(InDatum=df.Datum.isin(KBlatt[['erdat', 'erldat', 'aendat']].stack()).astype(int))
    

    Or with several conditions:

    df.assign(InDatum=(df.Datum.isin(KBlatt['erdat'])
                      |df.Datum.isin(KBlatt['erldat'])
                      |df.Datum.isin(KBlatt['aendat'])
                      ).astype(int)
              )