函数中的Apply方法不能处理函数

2024-04-26 11:33:57 发布

您现在位置:Python中文网/ 问答频道 /正文

我刚接触熊猫。以下是名为news的数据帧的子集合: Id是新闻的Id,文本列包括新闻:

Id             text
1              the news is really bad.
2              I do not have any courses.
3              Asthma is very prevalent.
4              depression causes disability.

我将计算“文本”栏中每条新闻的情绪。 我需要创建一个列来包含情绪分析的结果。你知道吗

这是我的密码:

    from textblob import TextBlob
    review = TextBlob(news.loc[0,'text'])
    print (review.sentiment.polarity)

此代码仅适用于文本列中的一条新闻。你知道吗

我还写了这个函数:

    def detect_sentiment(text):

        blob = TextBlob(text)
        return blob.sentiment.polarity

news['sentiment'] = news.text.apply(detect_sentiment)

但它有以下错误:

The `text` argument passed to `__init__(text)` must be a string, not <class 'float'>

有什么解决办法吗?你知道吗


Tags: 数据text文本idisnot新闻blob
1条回答
网友
1楼 · 发布于 2024-04-26 11:33:57

我无法重现您的错误:使用pandas==0.24.2Python 3.4.3,您的代码对我来说运行得非常好:

import pandas as pd
from textblob import TextBlob

news = pd.DataFrame(["the news is really bad.",
                   "I do not have any courses.",
                   "Asthma is very prevalent.",
                   "depression causes disability."], columns=["text"])

def detect_sentiment(text):
    blob = TextBlob(text)
    return blob.sentiment.polarity

news['sentiment'] = news.text.apply(detect_sentiment)

display(news)

结果:

+  +               -+      -+
|    | text                          |   sentiment |
|  +               -+      -|
|  0 | the news is really bad.       |        -0.7 |
|  1 | I do not have any courses.    |         0   |
|  2 | Asthma is very prevalent.     |         0.2 |
|  3 | depression causes disability. |         0   |
+  +               -+      -+

相关问题 更多 >