【问题标题】:Pandas.apply returning none value on spacy doc columnPandas.apply 在 spacy doc 列上返回无值
【发布时间】:2019-02-05 18:52:54
【问题描述】:

我在我的 pandas df 'sp500news3' 上运行以下命令,它返回 None 值

def extract_ticker(title):
    for word in title:
        if word in constituents['Symbol']:
            return word

sp500news3['tickers'] = sp500news3['title'].apply(extract_ticker)

#sp500news3 sample:



  index date_publish    title   tickers
0   79944   2007-01-29 19:08:35 (MSFT, Vista, corporate, sales, go, very, well) None
1   181781  2007-12-14 19:39:06 (WMB, No, Anglican, consensus, on, Episcopal, Church)   None
2   213175  2008-01-22 11:17:19 (CSX, quarterly, profit, rises) None
3   93554   2008-01-22 18:52:56 (C, says, 30, bln, capital, helps, exceed, target)  None

成分['符号']:示例

0      TWX  
1      C  
2      MSFT  
3      WMB ...

从以下复制 spacy 文档:

constituents =  pd.DataFrame({"Symbol":["TWX","C","MSFT","WMB"]})

sp500news3 = pd.DataFrame({"title":["MSFT Vista corporate sales go very well","WMB No Anglican consensus on Episcopal Church","CSX quarterly profit rises",'C says 30 bln capital helps exceed target','TWX plans cable spinoff']})

import spacy

nlp = spacy.load('en_core_web_sm')

sp500news3['title'] = sp500news3['title'].apply(nlp)

【问题讨论】:

  • 您期望发生什么? constituents 中的字符串似乎都没有出现在您的标题中。
  • 什么 dtype 是标题?它是字符串还是元组?大概 MSFT 在成分股中,这是第一个的预期结果?
  • 成分比样本长 - 包含所有 sp500 代码 - 期望从每个标题中提取代码并添加到 sp500news3 df 中的代码列
  • 标题的dtype是spacy.tokens.doc.Doc

标签: python pandas nlp spacy


【解决方案1】:

您必须使用word.text,因为当iterating over a spacy.tokens.doc.Doc 会迭代Token which doesn't implement __eq__ for strings

for word in title:
    if word.text in constituents['Symbol'].values:
        return word

用你的例子:

In [11]: sp500news3['title'].apply(extract_ticker)
Out[11]:
0    MSFT
1     WMB
2    None
3       C
4     TWX
Name: title, dtype: object

【讨论】:

  • 我想这不是“没有为字符串实现__eq__:”而是pandas不像它对字符串的特殊情况它的__eq__
  • 这仍然没有返回任何值,检查了constituents dtype 是str
  • @W.R 成分是字符串,但标题不是(你说它是 Doc)。请分享一个我们可以复制的示例。
  • 在发送到 spacy doc 之前添加了 df 和 spacy doc 的代码
  • 已添加constituentsdf
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2022-08-15
  • 1970-01-01
  • 2022-08-11
  • 1970-01-01
  • 1970-01-01
  • 2021-12-26
  • 1970-01-01
相关资源
最近更新 更多