【问题标题】:Pandas apply function to column then get attribute熊猫将函数应用于列然后获取属性
【发布时间】: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


【解决方案1】:

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

from operator import attrgetter

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

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

【讨论】:

    【解决方案2】:

    尝试创建一个返回所需值的自定义函数。

    def get_sentiment(x):
        _ = TextBlob(x)
        return _.sentiment
    
    df['comment'].apply(get_sentiment)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-02-07
      • 1970-01-01
      • 2021-02-12
      • 2016-09-13
      • 2018-11-13
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多