如何在python数据帧中过滤掉部分字符串

时间:2017-11-03 19:56:51

标签: python pandas

我的数据框有一个列['Busler Group'],它包含苹果,苹果,芒果,芒果等字符串。 我需要过滤出包含部分单词的列中的字符串,例如“app”或“man”。

以下是原始代码:

     AttributeError: Can only use .str accessor with string values, which              use 

      np.object_ dtype in pandas

这是错误:

{{1}}

2 个答案:

答案 0 :(得分:0)

演示:

In [2]: df
Out[2]:
        Busler Group
0   a regular string
1           an Apple
2  Do you like Mango
3      I hate mangos
4     Newton's apple
5     another string

In [3]: search_strings = ['app','man']

In [4]: pat = '(?:{})'.format('|'.join(search_strings))

In [5]: pat
Out[5]: '(?:app|man)'

In [7]: df = df[~df['Busler Group'].str.lower().str.contains(pat)]

In [8]: df
Out[8]:
       Busler Group
0  a regular string
5    another string

答案 1 :(得分:0)

它必须是.str工作的对象类型:

In [11]: s1 = pd.Series([1, 2, 3])

In [12]: s1.str.contains("2")
AttributeError: Can only use .str accessor with string values, which use np.object_ dtype in pandas

您可以通过使列str类型强制执行此操作:

In [13]: s1.astype(str).str.contains("2")
Out[13]:
0    False
1     True
2    False
dtype: bool
相关问题