Python 3.x 如何在遍历数据帧进行情绪分析时跳过np.nan

Python 3.x 如何在遍历数据帧进行情绪分析时跳过np.nan,python-3.x,pandas,boolean,nan,sentiment-analysis,Python 3.x,Pandas,Boolean,Nan,Sentiment Analysis,我有一个包含201279个条目的数据框,最后一列标有“文本”和客户评论。问题是,它们中的大多数都缺少值,并被称为NaN 我从这个问题中读到了一些有趣的信息: 我试着用它来解决我的问题: df1.columns Index(['id', 'sku', 'title', 'reviewCount', 'commentCount', 'averageRating', 'date', 'time', 'ProductName', 'CountOfBigTransactions'

我有一个包含201279个条目的数据框,最后一列标有“文本”和客户评论。问题是,它们中的大多数都缺少值,并被称为NaN

我从这个问题中读到了一些有趣的信息:

我试着用它来解决我的问题:

    df1.columns

Index(['id', 'sku', 'title', 'reviewCount', 'commentCount', 'averageRating',
       'date', 'time', 'ProductName', 'CountOfBigTransactions', 'ClassID',
       'Weight', 'Width', 'Depth', 'Height', 'LifeCycleName', 'FinishName',
       'Color', 'Season', 'SizeOrUtility', 'Material', 'CountryOfOrigin',
       'Quartile', 'display-name', 'online-flag', 'long-description', 'text'],
      dtype='object')
我试着这样做: df['firstName'][202360]==np.nan

返回
False
,但实际上该索引包含一个np.nan

因此,我寻找答案,通读我链接的问题,并看到了这一点

np.bool(df1['text'][201279])==True
这是一个真实的说法。我想,好吧,我可以用这个跑

到目前为止,我的代码如下:

from textblob import TextBlob
import string

def remove_num_punct(aText):
    p = string.punctuation
    d = string.digits
    j = p + d
    table = str.maketrans(j, len(j)* ' ')
    return aText.translate(table)

#Process text
aList = []
for text in df1['text']:
    if np.bool(df1['text'])==True:
        aList.append(np.nan)
    else:
        b = remove_num_punct(text)
        pol = TextBlob(b).sentiment.polarity
        aList.append(pol)
然后,我只需将带有情绪的
aList
转换为
pd.DataFrame
,并将其连接到
df1
,然后用K-最近邻填充缺失的值

我的问题是我做的小程序抛出了一个值错误

ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().
所以我真的不确定还能尝试什么。提前谢谢

编辑:我试过这个:

i = 0
aList = []
for txt in df1['text'].isnull():
    i += 1
    if txt == True:
        aList.append(np.nan)
正确地用NaN填充列表

但这给了我一个不同的错误:

i = 0
aList = []
for txt in df1['text'].isnull():
    if txt == True:
        aList.append(np.nan)
    else:
        b = remove_num_punct(df1['text'][i])
        pol = TextBlob(b).sentiment.polarity
        aList.append(pol)
        i+=1
AttributeError:“float”对象没有属性“translate”

这没有意义,因为如果它不是NaN,那么它包含文本,对吗

import pandas as pd
import numpy as np

df = pd.DataFrame({'age': [5, 6, np.NaN],
                   'born': [pd.NaT, pd.Timestamp('1939-05-27'), pd.Timestamp('1940-04-25')],
                   'name': ['Alfred', 'Batman', ''],
                   'toy': [None, 'Batmobile', 'Joker']})

df1 = df['toy']
for i in range(len(df1)):
    if not df1[i]:
        df2 = df1.drop(i)

df2

您可以尝试用这种方式来处理空文本

我修复了它,我必须将
I+=1
else
缩进移回
进行缩进:

i = 0
aList = []
for txt in df1['text'].isnull():
    if txt == True:
        aList.append(np.nan)
    else:
        b = remove_num_punct(df1['text'][i])
        pol = TextBlob(b).sentiment.polarity
        aList.append(pol)
    i+=1
好的,我可能会让df.isnull()工作,但如果在df1['text'的单个索引上使用,它会抛出一个错误