【问题标题】:Pandas: how to filter out rows containing a string pattern within a list in a column?Pandas:如何过滤掉列中列表中包含字符串模式的行?
【发布时间】:2022-11-02 16:55:07
【问题描述】:

我有一个类似于以下内容的数据框:

df = pd.DataFrame({
    'employee_id' : [123, 456, 789],
    'country_code' : ['US', 'CAN', 'MEX'],
    'comments' : (['good performer', 'due for raise', 'should be promoted'],
                 ['bad performer', 'should be fired', 'speak to HR'],
                 ['recently hired', 'needs training', 'shows promise'])
})

df

    employee_id   country_code   comments
0   123           US             [good performer, due for raise, should be promoted]
1   456           CAN            [bad performer, should be fired, speak to HR]
2   789           MEX            [recently hired, needs training, shows promise]

我希望能够将comments 列过滤为删除任何行包含字符串'performer'。为此,我正在使用:

df = df[~df['comments'].str.contains('performer')]

但是,这会返回一个错误:

TypeError: ufunc 'invert' not supported for the input types, and the inputs could not be safely coerced to any supported types according to the casting rule ''safe''

提前感谢您提供的任何帮助!

【问题讨论】:

    标签: pandas


    【解决方案1】:

    如果 IIUC 您需要将 cmets 列分解为字符串而不是列表

    df = pd.DataFrame({
        'employee_id' : [123, 456, 789],
        'country_code' : ['US', 'CAN', 'MEX'],
        'comments' : (['good performer', 'due for raise', 'should be promoted'],
                     ['bad performer', 'should be fired', 'speak to HR'],
                     ['recently hired', 'needs training', 'shows promise'])
    })
    df['comments'] = df['comments'].apply(lambda x : ' '.join(x))
    df = df[~df['comments'].str.contains('performer')]
    df
    

    【讨论】:

      【解决方案2】:

      由于您的系列中有列表,因此您无法进行矢量化。您可以使用列表推导:

      df2 = df[[all('performer' not in x for x in l)
                for l in df['comments']]]
      

      输出:

         employee_id country_code                                         comments
      2          789          MEX  [recently hired, needs training, shows promise]
      

      【讨论】:

        【解决方案3】:
        df = df[~df['comments'].map(' '.join).str.contains('performer')]
        

        【讨论】:

          猜你喜欢
          • 2019-02-21
          • 2017-08-15
          • 2022-06-20
          • 2015-12-23
          • 2022-11-17
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2019-06-01
          相关资源
          最近更新 更多