Pandas數(shù)據(jù)處理
這兩天在進行數(shù)據(jù)預處理時姑廉,發(fā)現(xiàn)在進行預料喂入時缺亮,總會出現(xiàn)錯誤:ValueError: not enough values to unpack (expected 2, got 1)
,但是在文本清洗時沒有顯示含有NaN的數(shù)據(jù)行,查看數(shù)據(jù)后發(fā)現(xiàn)有數(shù)據(jù)行為純空格桥言,但不會被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
這顯然沒有達到我的預期需求,因為切分數(shù)據(jù)時虫蝶,空格數(shù)據(jù)在過濾后為NaN值導致切分數(shù)據(jù)時出錯
解決方法
直接使用Series的.apply方法來修改變量text中的每個值章咧。如果發(fā)現(xiàn)是空格,就返回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>