python-3.x - 熊猫将函数应用于列然后获取属性
问题描述
我正在尝试将函数应用于熊猫列,然后检索函数的属性。具体来说,我使用 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)
如何应用函数并获取列的属性?
解决方案
你可以attrgetter
在这里使用,这是一个“咖喱”版本getattr
:
from operator import attrgetter
df.comment.apply(TextBlob).apply(attrgetter('sentiment'))
但是,如果TextBlob
是“矢量化”,则可能有一种更有效的方法来计算所有项目的情绪,但目前尚不清楚如何TextBlob
实现。
推荐阅读
- odata - 是否可以将记录添加到 oData 模型,以便在 UI 上可见且无需发布?
- javascript - 从 URL 中删除查询
- python - 第二次执行代码时spyder没有响应
- odoo-12 - 停止 longpolling cron 调用以轻松调试
- .net - .NET 到 Docker Hub 构建成功但发布失败
- saml-2.0 - 签署 SAML 消息 - LightSAML SPBundle 配置
- sql - 使用 Group By 子句查询
- java - java - 如何在java spring中只运行一次方法?
- c# - 允许用户从 Web.config 获得 IIS 授权角色
- python - django-filter - 如何解析带有后缀的字段名称,例如“_id”(动态字段名称)