【问题标题】:How to find all rows in a dataframe that contain a substring?如何在包含子字符串的数据框中查找所有行?
【发布时间】:2017-08-12 02:42:55
【问题描述】:

我有一个单词和一个带有一列字符串值的 Pandas 数据框。现在我正在尝试在该数据框中查找在其字符串部分中包含该单词的行。

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

【问题讨论】:

标签: python string pandas dataframe string-matching


【解决方案1】:

使用这个测试数据(修改并借自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)]

【讨论】:

    【解决方案2】:

    使用 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
    

    【讨论】:

      【解决方案3】:

      使用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
      

      【讨论】:

        猜你喜欢
        • 2016-10-19
        • 2013-07-11
        • 2012-06-28
        • 2015-02-18
        • 1970-01-01
        • 1970-01-01
        • 2013-05-13
        • 2011-03-11
        • 1970-01-01
        相关资源
        最近更新 更多