Home > Mobile >  Boolean indexing pandas df, value in list of values
Boolean indexing pandas df, value in list of values

Time:05-17

Need to locate dataframe rows having col value equal to one of the values contained in a list. I tried:

values_to_match=[v1, v2, v3]

df[df.col in values_to_match]

and this error pop up:

  ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().

I cannot do something like this:

 df[(df.col==values_to_match[0] or (df.col==values_to_match[1] or (df.col==values_to_match[2]) ]

because my values_to_match list does not have a fixed lenght.

Thank you

CodePudding user response:

I would use a np.where() to get the results you are wanting

import pandas as pd
import numpy as np

values_to_match=['v1', 'v2', 'v3']

data = {'Column_1' : ['v1', 'v2', 'v3', 'v4']}
df = pd.DataFrame(data)
df['Check'] = np.where(df['Column_1'].isin(values_to_match), True, False)
df.loc[df['Check'] == True]
  • Related