【问题标题】:Select rows in Pandas which does not contain a specific character在 Pandas 中选择不包含特定字符的行
【发布时间】:2017-01-20 00:50:15
【问题描述】:

我需要类似的东西

.str.startswith() 
.str.endswith()

但对于字符串的中间部分。

例如,给定以下 pd.DataFrame

      str_name
   0    aaabaa
   1    aabbcb
   2    baabba
   3    aacbba
   4    baccaa
   5    ababaa

我需要抛出包含(至少一个)字母“c”的第 1、3 和 4 行。
特定字母 ('c') 的位置未知。
任务是删除所有包含至少一个特定字母的行

【问题讨论】:

    标签: python pandas


    【解决方案1】:

    你想要df['string_column'].str.contains('c')

    >>> df
      str_name
    0   aaabaa
    1   aabbcb
    2   baabba
    3   aacbba
    4   baccaa
    5   ababaa
    >>> df['str_name'].str.contains('c')
    0    False
    1     True
    2    False
    3     True
    4     True
    5    False
    Name: str_name, dtype: bool
    

    现在,你可以像这样“删除”

    >>> df = df[~df['str_name'].str.contains('c')]
    >>> df
      str_name
    0   aaabaa
    2   baabba
    5   ababaa
    >>>
    

    编辑添加:

    如果只想查看k 的前几个字符,可以slice。假设k=3

    >>> df.str_name.str.slice(0,3)
    0    aaa
    1    aab
    2    baa
    3    aac
    4    bac
    5    aba
    Name: str_name, dtype: object
    >>> df.str_name.str.slice(0,3).str.contains('c')
    0    False
    1    False
    2    False
    3     True
    4     True
    5    False
    Name: str_name, dtype: bool
    

    注意,Series.str.slice 的行为不像典型的 Python 切片。

    【讨论】:

    • 谢谢!如果我想检查 'str_name' 中是否只有前 k 个字母包含 ''c' 怎么办?
    • 所以“~”的意思是倒数?我必须尝试一下——学到了一些新东西。 df = df[~df['str_name'].str.contains('c')]
    • @ArthurD.Howland ~是向量化逻辑否定,所以相当于not,同理and对应&or对应|跨度>
    【解决方案2】:

    你可以使用numpy

    df[np.core.chararray.find(df.str_name.values.astype(str), 'c') < 0]
    
      str_name
    0   aaabaa
    2   baabba
    5   ababaa
    

    【讨论】:

      【解决方案3】:

      你可以使用 str.contains()

      str_name = pd.Series(['aaabaa', 'aabbcb', 'baabba', 'aacbba',  'baccaa','ababaa'])
      str_name.str.contains('c')
      

      这将返回布尔值

      下面将返回上面的反函数

      ~str_name.str.contains('c')
      

      【讨论】:

        猜你喜欢
        • 2018-08-07
        • 1970-01-01
        • 2021-11-28
        • 1970-01-01
        • 2015-10-17
        • 2021-12-13
        • 1970-01-01
        • 2016-05-28
        • 2021-12-01
        相关资源
        最近更新 更多