Search code examples
pythonstringlistcomparisonoperator-keyword

Find ia a strn column is in a list column in the same data frame and create a 3rd column with a value


I have this data frame with 2 columns, "Column A" and "Column B", Column A is a string and column B is a list:

A        B                               c
cat      | cat | elephant | gorilla |    YES
dog      | monkey | duck | giraffe |     NO
bird     | cow | bird | hamster |        YES

and I want to evaluate if Column A is in Column B and if so to write YES or NO in this new column C

I tried many ways, the very last one is:

df_epl["Marketo LSC"] = df_epl["Data Entry Point"].isin("Entry Point List")

but it gives me this error:

in isin

raise TypeError(TypeError: only list-like objects are allowed to be passed to isin(), you passed a [str]

Solution

  • Try this

    import pandas as pd
    df = pd.read_csv('res.csv') #Your csv here
    C = []
    for i in range(0,len(df)):
      if df['A'][i] in df['B'][i]:
        C.append('YES')
      else:
        C.append('NO')
    df['C'] = C
    print(df)