我有一个包含201279个条目的数据框,最后一列是带有客户评论的“文本”。问题是它们中的大多数都缺少值,并以NaN的形式出现。
我从这个问题中读到了一些有趣的信息:Python numpy.nan and logical functions: wrong results
我试着把它应用到我的问题上:
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‘== 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+=1AttributeError: 'float' object has no attribute 'translate'
这没有任何意义,因为如果它不是NaN,那么它就包含文本,对吧?
发布于 2019-03-07 14:20:09
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您可以尝试以这种方式处理为空的文本
发布于 2019-03-07 18:18:53
我修复了它,我必须将i += 1从else缩进移回for缩进:
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+=1https://stackoverflow.com/questions/55036276
复制相似问题