我在进行情绪分析时遇到了一个类型错误,如何解决这个问题?

2024-04-16 09:42:32 发布

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

我正在对比特币新闻进行情绪分析。在我编写代码的过程中,出现了一个类型错误问题。我希望你能帮助我,并提前非常感谢你!你知道吗

from newsapi.newsapi_client import NewsApiClient
from textblob import TextBlob
import pandas as pd
import numpy as np
from bs4 import BeautifulSoup
import datetime
from datetime import time
import csv
from dateutil import parser

api = NewsApiClient(api_key='my key')

all_articles = api.get_everything(q='bitcoin',
                                      sources='bbc-news,the-verge,financial-times,metro,business-insider,reuters,bloomberg,cnbc,cbc-news,fortune,crypto-coins-news',
                                      domains='bbc.co.uk,techcrunch.com',
                                      from_param='2019-10-20',
                                      to='2019-11-19',
                                      language='en',
                                      sort_by='relevancy',
                                      page_size=100)

news= pd.DataFrame(all_articles['articles'])

news['polarity'] = news.apply(lambda x: TextBlob(x['description']).sentiment.polarity, axis=1)
news['subjectivity'] = news.apply(lambda x: TextBlob(x['description']).sentiment.subjectivity, axis=1)
news['date']= news.apply(lambda x: parser.parse(x['publishedAt']).strftime('%Y.%m.%d'), axis=1)
news['time']= news.apply(lambda x: parser.parse(x['publishedAt']).strftime('%H:%M'), axis=1)

然后出现以下类型错误: imgur_link


Tags: lambdafromimportapiparser类型as错误
2条回答

你需要调试你的代码。您正在传递None值。你知道吗

x['description']可能有一些None值。你知道吗

news['polarity'] = news.apply(lambda x: TextBlob(x['description']).sentiment.polarity, axis=1)

确保在预处理阶段,在dataframe中没有任何NoneNaN

正如@Hayat正确指出的,description列中的某些行具有None值,这些值导致了异常。共有四行,请参见下面的屏幕截图。你知道吗

Rows with <code>None</code> in <code>description</code> column

您应该删除这些行,并对具有正确数据的行进行操作。您可以使用筛选在description列中有None的行

news_filtered = news[news['description'].notnull()]
news_filtered['polarity'] = news_filtered.apply(lambda x: TextBlob(x['description']).sentiment.polarity, axis=1)

您可能需要对其他列重复上述操作。你知道吗

相关问题 更多 >