【问题标题】:Contains one of several values包含多个值之一
【发布时间】:2018-08-07 09:26:58
【问题描述】:

我有一个数据框 df 与列 x 和一个列表 lst =["apple","peach","pear"]

df  
x               
apple234  
pear231  
banana233445 

如果df["x"] 中的row1 包含lst 中的任何值:则1 否则0

最终数据应如下所示:

df  
x  y  
apple234  -- 1  
pear231 -- 1    
banana233445 - 0 

【问题讨论】:

    标签: python loops contains


    【解决方案1】:

    使用str.contains 和正则表达式| 连接列表的所有值,最后通过astype 将布尔掩码转换为0,1

    lst =["apple","peach","pear"]
    
    df['y'] = df['x'].str.contains('|'.join(lst)).astype(int)
    print (df)
                  x  y
    0      apple234  1
    1       pear231  1
    2  banana233445  0
    

    【讨论】:

    • 非常感谢。那行得通。但是,如果你能解释一下 '.contains('|'.join(lst)
    • 这真的很简单 - print('|'.join(lst)) -> apple|peach|pear 这意味着检查 apple OR peach OR pear 是否在列中 - contains 通过这个连接的字符串过滤它。
    猜你喜欢
    • 2012-08-22
    • 2016-10-02
    • 1970-01-01
    • 2014-06-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多