Pandas Dataframe:如果A,B或C列中的行包含“x”或" y",请将“z”写入新列

时间:2018-02-21 12:37:38

标签: python pandas dataframe contains

与此问题非常相似:Pandas: if row in column A contains "x", write "y" to row in column B

我想知道一行是否包含" x"或" y"在多个不同的列中输出" z"到新专栏。

INPUT:

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

如果" cat"或者" tiger"或者"狮子" - 输出1到新列

输出

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

1 个答案:

答案 0 :(得分:1)

isinanyastype

一起使用
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