【问题标题】:How to choose values from col1 if their values are in col2 but not on list in Python Pandas?如果它们的值在 col2 中但不在 Python Pandas 的列表中,如何从 col1 中选择值?
【发布时间】:2021-06-26 01:35:53
【问题描述】:

我在 Python Pandas 中有 DataFrame,如下所示:

col1       | description
---------- |-----------
John Simon |John Simon red
Terry Juk  |green Terry Juk
John Bravo |John Bravo brown
Ann Still  |orange Ann Still

bad_list = ["red", "green"]

我只需要从“col1”中选择这些人,这些人在“description”列中的“col”和其他内容(不管之前或之后)中具有价值,但其他内容不能来自 bad_list。

所以我只需要选择 John Bravo 和 Ann Still,因为它们在“description”列中具有来自“col1”的值,并且在“description”列中没有带有其名称的 bad_list 单词。

如何在 Python Pandas 中做到这一点?

【问题讨论】:

    标签: python pandas dataframe


    【解决方案1】:

    试试:

    bad_list = ["red", "green"]
    
    mask = df["description"].str.contains(r"|".join(bad_list))
    print(df.loc[~mask, "col1"])
    

    打印:

    2    John Bravo
    3     Ann Still
    Name: col1, dtype: object
    

    编辑:检查来自col1 的值是否在描述中:

    bad_list = ["red", "green"]
    
    mask1 = df["description"].str.contains(r"|".join(bad_list))
    mask2 = df.apply(lambda x: x["col1"] in x["description"], axis=1)
    print(df.loc[~mask1 & mask2, "col1"])
    

    EDIT2:忽略大小写:

    import re
    
    bad_list = ["RED", "green"]
    
    mask1 = df["description"].str.contains(r"|".join(bad_list), flags=re.I)
    mask2 = df.apply(lambda x: x["col1"] in x["description"], axis=1)
    print(df.loc[~mask1 & mask2, "col1"])
    

    【讨论】:

    • 我认为你错过了 col1 的值应该出现在描述中的一点
    • 安德烈·凯塞利,干得好!最佳答案!但是我的方式,是否也可以管理坏列表中的字母大小?因为有时我可以有“红色”或“红色”或“红色”?如何处理?
    • @gato 查看我的 EDIT2
    • 谢谢!完美的!我肯定给了最好的答案!
    • 好的,Andrej,我会创建一个新问题并给你一个链接
    猜你喜欢
    • 2019-05-22
    • 2018-06-13
    • 2020-02-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-12-16
    相关资源
    最近更新 更多