.dropna()不能从pandas Datafram中删除所有NaN

2024-09-30 14:23:39 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个代码,其中我过滤掉一些停止字和特殊字符。dropna()过滤掉了大部分现有的NaN,但是cleaner = clean.str.replace('#|\|_|!|.|\^|:|(|)|-|\?|!|\,','') 行在csv文件中创建了一些新的NaN(有些行只是特殊字符),这些不会被过滤掉。我怎样才能把这些过滤掉呢?在

import pandas as pd
from stop_words  import get_stop_words

df = pd.read_csv("F:/textclustering/data/cleandata.csv", encoding="iso-8859-1")

usertext = df[df.Role.str.contains("End-user",na=False)][['Data','chatid']]
lowertext = usertext['Data'].map(lambda x: x if type(x)!=str else x.lower())

nl_stop_words = get_stop_words('dutch')
stop_words_pat = '|'.join(['\\b' + stop +  '\\b' for stop in nl_stop_words])
clean = lowertext.str.replace(stop_words_pat, '')
cleaner = clean.str.replace('\#|\|\_|\!|\.|\^|\:|\(|\)|\-|\?|\!|\,','')

render = pd.concat([cleaner, usertext['chatid']], axis=1)
#print(render)
#print(type(render))

final= render.dropna(how='any')

final.to_csv("F:/textclustering/data/filteredtext.csv", sep=',',index=False, encoding="iso-8859-1")

df2 = pd.read_csv("F:/textclustering/data/filteredtext.csv", encoding="iso-8859-1")

print(df2)

更新:原始数据

^{pr2}$

(出于隐私考虑,我已将荷兰语文本替换为lorum impsum) 最后一行是NaN


Tags: csvcleandfdataisonanrenderreplace