【问题标题】:How can I drop rows in a dataframe efficiently ir a specific column contains a substring [duplicate]如何在特定列包含子字符串时有效地删除数据框中的行[重复]
【发布时间】:2019-02-17 09:28:44
【问题描述】:

我试过了

df = df[~df['event.properties.comment'].isin(['Extra'])]

问题是如果该列正好包含“Extra”,它只会删除该行,我需要删除包含它的行,甚至作为子字符串。

有什么帮助吗?

【问题讨论】:

    标签: python string pandas dataframe series


    【解决方案1】:

    您可以使用 or 条件来检查字符串的多个条件,根据您的要求,如果文本具有“Extra”或“~”,您可以保留文本。 考虑df

        vals    ids
    0   1   ~
    1   2   bball
    2   3   NaN
    3   4   Extra text
    
    df[~df.ids.fillna('').str.contains('Extra')]
    

    输出:

        vals    ids
    0   1   ~
    1   2   bball
    2   3   NaN
    

    【讨论】:

    • 我有 2 个问题:1. NaN 值,2. 使用时 ~ (我需要保留不包含单词的那些)出现此错误:一元操作数类型错误 ~ : '浮动'
    • @AdrianTorrejón 听起来您的列中有空值。 Pandas 将所有 null 视为 NaN(它们始终是浮点数,因为 pandas 目前是在 numpy 之上构建的)。你必须为你的 NaN 选择一个合适的字符串映射。
    • OP 想要删除包含 extra 的行,您的解决方案是保留这些行并删除其余行
    • 谢谢,完美运行!有什么办法让它对大小写不敏感?
    • df[~df.ids.fillna('').str.contains('Extra',case=False)]
    猜你喜欢
    • 2020-09-27
    • 2015-04-25
    • 2016-01-05
    • 2021-10-09
    • 2017-05-23
    • 2018-02-25
    • 2020-02-04
    • 1970-01-01
    • 2021-03-17
    相关资源
    最近更新 更多