【问题标题】:Pandas Dataframe: if row in column A, B or C contains “x” or "y", write “z” to new columnPandas Dataframe:如果 A、B 或 C 列中的行包含“x”或“y”,则将“z”写入新列
【发布时间】:2018-02-21 12:37:38
【问题描述】:

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

我想知道一行是否在多个不同的列中包含“x”或“y”,然后将“z”输出到新列。

输入:

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

如果 "cat" 或 "tiger" 或 "lion" - 输出 1 到新列

输出

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

【问题讨论】:

    标签: python pandas dataframe contains


    【解决方案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
    

    【讨论】:

    • 干杯,很干净
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-04-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多