【问题标题】:pandas dataframe extract strings熊猫数据框提取字符串
【发布时间】:2016-07-12 21:00:54
【问题描述】:

我的数据框有一个名为“a”的列,它可能包含“apple”和“orange”。我想要的是提取它们(如果存在),否则标记为“其他”。

我可以简单地遍历行并提取它们。但是,我看到numpy.where() 用于类似目的的一些用法,但只有两个类别。

result = numpy.where(df['a'].str.contains('apple'), 'apple', 'others')

是否可以将其应用于3个类别的情况?换句话说,result 应该包含“apple”、“orange”或“others”的条目。

有没有比简单循环更好的方法?

【问题讨论】:

    标签: numpy pandas dataframe text-extraction


    【解决方案1】:

    只需使用np.in1d 查找applemango 的项目即可创建一个布尔掩码,然后可以将其与np.where 一起使用以将其余项目设置为others。因此,我们会有 -

    df['b'] = np.where(np.in1d(df.a,['apple','orange']),df.a,'others')
    

    如果您可能希望使用将这些名称作为较大字符串的一部分的字符串,您可以使用str.extract(从@jezrael's solution 获得这个想法,我希望没关系!)然后使用@987654330 @,就像这样 -

    strings = df.a.str.extract('(orange|apple)')
    df['b'] = np.where(np.in1d(strings,['apple','orange']),strings,'others')
    

    示例运行 -

    In [294]: df
    Out[294]: 
                 a
    0  apple-shake
    1       orange
    2  apple-juice
    3        apple
    4        mango
    5       orange
    6       banana
    
    In [295]: strings = df.a.str.extract('(orange|apple)')
    
    In [296]: df['b'] = np.where(np.in1d(strings,['apple','orange']),strings,'others')
    
    In [297]: df
    Out[297]: 
                 a       b
    0  apple-shake   apple
    1       orange  orange
    2  apple-juice   apple
    3        apple   apple
    4        mango  others
    5       orange  orange
    6       banana  others
    

    【讨论】:

      【解决方案2】:

      str.extractfillna 一起使用:

      df = pd.DataFrame({'a': ['orange','apple','a']})
      print (df)
              a
      0  orange
      1   apple
      2       a
      
      df['new'] = df.a.str.extract('(orange|apple)', expand=False).fillna('others')
      print (df)
              a     new
      0  orange  orange
      1   apple   apple
      2       a  others
      

      【讨论】:

      • 我希望结果是 3 种可能性之一:'apple'、'orange' 或 'others'。
      猜你喜欢
      • 1970-01-01
      • 2020-06-03
      • 2017-02-24
      • 1970-01-01
      • 2021-02-11
      • 2021-05-25
      • 2021-01-31
      • 2022-11-18
      • 2020-03-07
      相关资源
      最近更新 更多