0

Very similar to this question: Pandas: if row in column A contains "x", write "y" to row in column B

I want to know if a row contains "x" or "y" in multiple different columns then output "z" to a new column.

INPUT:

A        B        C
Cat      Dog     Pig
Monkey   Tiger   Cat
Cow      Sheep   Goat

If "cat" or "tiger" or "lion" - output 1 to new column

OUTPUT

A        B        C       CAT FAMILY
Cat      Dog     Pig          1
Monkey   Tiger   Cat          1
Cow      Sheep   Goat         0

1 Answers1

1

Use isin with any and astype

In [298]: cat_family = ["Cat", "Tiger", "Lion"]

In [303]: df['CAT_FAMILY'] = df.isin(cat_family).any(1).astype(int)

In [304]: df
Out[304]:
        A      B     C  CAT_FAMILY
0     Cat    Dog   Pig           1
1  Monkey  Tiger   Cat           1
2     Cow  Sheep  Goat           0
Zero
  • 74,117
  • 18
  • 147
  • 154