Skip to main content
 首页 » 编程设计

Python Pandas CSV 导入/Unicode 问题

2025年04月02日13小虾米

我正在处理留言板帖子(包含在 CSV 文件中),尝试在训练分类模型之前清理数据等。

事情进展顺利,直到我得到:

TypeError: 'float' object is not iterable

响应行:

letters_only = ''.join([i for i in textToProcess if not i.isdigit()]) 

textToProcess 来自 (train["text"][i])。

所以...当我想通过调用来检查我的数据时:

print train.isnull().sum() 
print test.isnull().sum() 

我得到了以下输出:

id          0 
category    0 
title       0 
text        1 
train       26 
dtype:      int64 
id          5512 
category    5512 
title       5512 
text        5512 
train       5512 
dtype: int64 

问题:所以我的意思是在测试集中,每列有5512个空值?

这会很奇怪,因为在这一点之前,导入等在大多数情况下表现得都符合预期。例如,调用 e.g. train["text"][0] 产生了预期的输出(即文本)。

如果有帮助,我原来的 read_csv 导入调用如下所示:

train = pd.read_csv(full_train_filename, header=0, encoding = 'utf-8') 
 
test = pd.read_csv(full_test_filename, header=0, encoding = 'utf-8')` 

我不确定这里是否有一个直接的问题,但我希望有人看到我做错了什么。

如有任何想法,我们将不胜感激。

请您参考如下方法:

我认为您需要检查 DataFrame 中的 NaN 值,它是从 csv 创建的。您可以使用 isnull与 any和 boolean indexing :

test[test.isnull().any(1)] 

示例:

import pandas as pd 
import numpy as np 
 
test = pd.DataFrame({'a': {0: 'r', 1: 'r', 2: 't', 3: 'y'},  
                     'b': {0: 'a', 1: 'a', 2: 's', 3: 'g'},  
                     'c': {0: 7.0, 1: 5.0, 2: np.nan, 3: 4.0}}) 
print (test) 
   a  b    c 
0  r  a  7.0 
1  r  a  5.0 
2  t  s  NaN 
3  y  g  4.0 
 
print (test[test.isnull().any(1)]) 
   a  b   c 
2  t  s NaN 

然后你可以使用一些文本编辑器,例如Notepad++ 并检查这个有问题的行。