【发布时间】:2020-01-15 17:18:23
【问题描述】:
我正在尝试将函数应用于 pandas 列,然后检索函数的属性。具体来说,我使用 TextBlob 从意见列中提取情绪和极性。
这是我尝试运行的示例代码。
opinion = ['good', 'bad','horrible']
df = pd.DataFrame(opinion, columns=['comment'])
df.head()
comment
0 good
1 bad
2 horrible
我试图运行的伪代码是
from textblob import TextBlob
df['sentiment'] = df.comment.apply(TextBlob).sentiment
这会引发 AttributeError。
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
in
----> 1 df.comment.apply(TextBlob).sentiment
~\AppData\Local\Continuum\miniconda3\lib\site-packages\pandas\core\generic.py in __getattr__(self, name)
5177 if self._info_axis._can_hold_identifiers_and_holds_name(name):
5178 return self[name]
-> 5179 return object.__getattribute__(self, name)
5180
5181 def __setattr__(self, name, value):
AttributeError: 'Series' object has no attribute 'sentiment'
我正在考虑使用getattr() 函数,但它不起作用。
df.comment.apply(TextBlob).apply(getattr,sentiment)
如何应用函数并获取列的属性?
【问题讨论】:
-
df['sentiment'] = df.comment.apply(TextBlob).sentiment这是什么意思?您只是定义了情绪列,您打算如何通过.sentiment访问它? -
可能你需要
df.assign(sentiment = df.comment.apply(TextBlob)).sentiment -
你能指定
TextBlob来自哪里吗? -
@WillemVanOnsem 我已经在上面添加了包导入语句。
标签: python-3.x pandas dataframe apply