首页 > 解决方案 > 熊猫将函数应用于列然后获取属性

问题描述

我正在尝试将函数应用于熊猫列,然后检索函数的属性。具体来说,我使用 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)

如何应用函数并获取列的属性?

标签: python-3.xpandasdataframeapply

解决方案


你可以attrgetter在这里使用,这是一个“咖喱”版本getattr

from operator import attrgetter

df.comment.apply(TextBlob).apply(attrgetter('sentiment'))

但是,如果TextBlob是“矢量化”,则可能有一种更有效的方法来计算所有项目的情绪,但目前尚不清楚如何TextBlob实现。


推荐阅读