【问题标题】:Search over text column in pandas data frame without looping在熊猫数据框中搜索文本列而不循环
【发布时间】:2017-12-20 19:42:53
【问题描述】:

我有一个 pandas 数据框,其中一列是文本描述字符串。我需要创建一个新列,用于识别列表中的一个字符串是否在文本描述中。

df = pd.DataFrame({'Description': ['2 Bedroom/1.5 Bathroom end unit Townhouse.  
Available now!', 'Very spacious studio apartment available', ' Two bedroom, 1 
bathroom condominium, superbly located in downtown']})

list_ = ['unit', 'apartment']

那么结果应该是

                                        Description    in list
0  2 Bedroom/1.5 Bathroom end unit Townhouse.  Av...    True
1           Very spacious studio apartment available    True
2   Two bedroom, 1 bathroom condominium, superbly...   False

我可以这样做

for i in df.index.values:
    df.loc[i,'in list'] = any(w in df.loc[i,'Description'] for w in list_)

但是对于大型数据集,它需要的时间比我想的要长。

【问题讨论】:

    标签: python pandas nlp


    【解决方案1】:

    通过使用str.contains

    list_ = ['unit', 'apartment']
    df.Description.str.contains('|'.join(list_))
    Out[724]: 
    0     True
    1     True
    2    False
    Name: Description, dtype: bool
    

    【讨论】:

      【解决方案2】:

      使用np.char.find -

      v = df.Description.values.astype('U')[:, None]
      df['in list'] = (np.char.find(v, list_) > 0).any(1)
      
      df
      
                                               Description  in list
      0  2 Bedroom/1.5 Bathroom end unit Townhouse.  Av...     True
      1           Very spacious studio apartment available     True
      2   Two bedroom, 1 bathroom condominium, superbly...    False
      

      【讨论】:

      • 学习新事物:-)
      • @Wen 干杯!知道这很有趣,但我认为它比str.contains 慢。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-05-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-11-18
      相关资源
      最近更新 更多