如何查找包含子字符串的数据框中的所有行?

时间:2017-03-20 17:24:20

标签: python string pandas dataframe string-matching

我有一个单词和一个带有一列字符串值的Pandas数据框。现在,我试图找到该数据帧中包含该字符串部分中该字的行。

我读到了 extractall()方法,但我不确定如何使用它,或者它是否是正确答案。

3 个答案:

答案 0 :(得分:3)

使用此测试数据(修改并借鉴Chris Albon):

raw_data = {'regiment': ['Nighthawks Goons', 'Nighthawks Goons', 'Nighthawks', 'Nighthawks', 'Dragoons', 'Dragoons', 'Dragoons', 'Dragoons', 'Scouts', 'Scouts', 'Scouts', 'Scouts'],
        'company': ['1st', '1st', '2nd', '2nd', '1st', '1st', '2nd', '2nd','1st', '1st', '2nd', '2nd'],
        'name': ['Miller', 'Jacobson', 'Ali', 'Milner', 'Cooze', 'Jacon', 'Ryaner', 'Sone', 'Sloan', 'Piger', 'Riani', 'Ali'],
        'preTestScore': [4, 24, 31, 2, 3, 4, 24, 31, 2, 3, 2, 3],
        'postTestScore': [25, 94, 57, 62, 70, 25, 94, 57, 62, 70, 62, 70]}
df = pd.DataFrame(raw_data, columns = ['regiment', 'company', 'name', 'preTestScore', 'postTestScore'])

您可以使用它来查找仅包含单词goons的行(我忽略了这种情况):

df[df['regiment'].str.contains(r"\bgoons\b", case = False)]

答案 1 :(得分:2)

使用str.contains

df.mycolumn.str.contains(myword)

<强> 示范

myword = 'foo'
df = pd.DataFrame(dict(mycolumn=['abc', '__foo__']))

df.mycolumn.str.contains(myword)

0    False
1     True
Name: mycolumn, dtype: bool

答案 2 :(得分:0)

使用jato的例子。

In [148]: df[['Goons' in i for i  in  df.regiment]]
Out[148]:
           regiment company      name  preTestScore  postTestScore
0  Nighthawks Goons     1st    Miller             4             25
1  Nighthawks Goons     1st  Jacobson            24             94