Search code examples
pythonstringpandasdataframeisin

Add column containing list value if column contains string in list


I'm trying to scan a particular column in a dataframe, eg df['x'] for values which I have in a separate list list = ['y', 'z', 'a', 'b']. How do I make pandas load a new column with the list value if df['x'] contains any, or more than one of the values from the list?

Thanks!


Solution

  • Use this:

    In [720]: import pandas as pd
    In [719]: if df['x'].str.contains('|'.join(list)).any(): 
         ...:     df = pd.concat([df, pd.DataFrame(list)], axis=1)) 
         ...: