Pandas数据处理
这两天在进行数据预处理时,发现在进行预料喂入时,总会出现错误:ValueError: not enough values to unpack (expected 2, got 1),但是在文本清洗时没有显示含有NaN的数据行,查看数据后发现有数据行为纯空格,但不会被df.isnull().any()查看到,记录下解决办法。
问题示例
data = {'id':[1,2,3],
'text':['The title is fine as it is.','Explanation\nWhy the edits made under my usern',' ']}
df = pd.DataFrame(data)
df
id text
0 1 The title is fine as it is.
1 2 Explanation\nWhy the edits made under my usern
2 3
df.isnull().any()
-------------------
id False
text False
dtype: bool
这显然没有达到我的预期需求,因为切分数据时,空格数据在过滤后为NaN值导致切分数据时出错
解决方法
直接使用Series的.apply方法来修改变量text中的每个值。如果发现是空格,就返回NaN,否则就返回原值。
df["text"]=df["text"].apply(lambda x: np.NaN if str(x).isspace() else x)
df
df.isnull().any()
-------------------
id False
text True
dtype: bool
df[df.isnull().values==True]
-----------------------------
id text
2 3 NaN
另一种情况
text
0 <review id="5000">\n
1 \n
2 看过此人在百家讲坛的演讲\n
3 \n
4 </review>\n
使用df[text_field] = df[text_field].str.replace(r"[\n]", "")方法去除了\n后,不清楚原因是什么,使用上面的方法没有效果,但用data.to_csv()方法写出到文件后,再从新读取就可以了
comment_text
0 <review id="5000">
1 NaN
2 看过此人在百家讲坛的演讲。
3 NaN
4 </review>