0

Can't I use a isin within a lambda function. E.g.

mylist = ["A", "B", "C"]
df["Col2"] = df["Col1"].apply(lambda x: 1 if x.isin(mylist) else 0)

I'm getting an AttributeError: 'str' object has no attribute 'isin' but the following filter works though:

df[df["Col1"].isin(mylist)]
42piratas
  • 555
  • 1
  • 9
  • 26
  • 1
    `.isin` is a method for pandas Series, the `x` within lambda is a string, which does not have `.isin` method. – TYZ Jan 07 '21 at 20:48
  • 1
    What's your question? `isin` is a `pd.Series` method. When you `apply` on a series, `x` is the value in a cell, which is string. Of course string doesn't have `.isin` method. – Quang Hoang Jan 07 '21 at 20:48
  • `df["Col2"] = df['Col1'].isin(mylist).astype(int)` – Quang Hoang Jan 07 '21 at 20:49
  • df["Col1"].apply(lambda x: 1 if x in mylist else 0) – BENY Jan 07 '21 at 20:53

1 Answers1

3

Use the in operator.

Replace x.isin(mylist) with x in mylist as follows:

df["Col2"] = df["Col1"].apply(lambda x: 1 if x in mylist else 0)
I_Am_Yohan
  • 176
  • 1
  • 9