如何避免解码到str:在熊猫中需要类似字节的对象错误?

way*_*001 5 python python-3.x pandas gensim topic-modeling

这是我的代码:

data = pd.read_csv('asscsv2.csv', encoding = "ISO-8859-1", error_bad_lines=False);
data_text = data[['content']]
data_text['index'] = data_text.index
documents = data_text
Run Code Online (Sandbox Code Playgroud)

看起来像

print(documents[:2])
                                              content  index
 0  Pretty extensive background in Egyptology and ...      0
 1  Have you guys checked the back end of the Sphi...      1
Run Code Online (Sandbox Code Playgroud)

我使用gensim定义了一个预处理函数

stemmer = PorterStemmer()
def lemmatize_stemming(text):
    return stemmer.stem(WordNetLemmatizer().lemmatize(text, pos='v'))
def preprocess(text):
    result = []
    for token in gensim.utils.simple_preprocess(text):
        if token not in gensim.parsing.preprocessing.STOPWORDS and len(token) > 3:
            result.append(lemmatize_stemming(token))
    return result
Run Code Online (Sandbox Code Playgroud)

当我使用此功能时:

processed_docs = documents['content'].map(preprocess)
Run Code Online (Sandbox Code Playgroud)

它出现

TypeError: decoding to str: need a bytes-like object, float found
Run Code Online (Sandbox Code Playgroud)

如何将我的csv文件编码为类似字节的对象,或者如何避免这种错误?

Vis*_*dev 5

您的数据有NaNs(不是数字)。

您可以先删除它们:

documents = documents.dropna(subset=['content'])
Run Code Online (Sandbox Code Playgroud)

或者,您可以NaNs用空字符串填充所有内容,将列转换为字符串类型,然后映射基于字符串的函数。

documents['content'].fillna('').astype(str).map(preprocess)
Run Code Online (Sandbox Code Playgroud)

这是因为您的函数预处理具有仅接受字符串数据类型的函数调用。

编辑:

我怎么知道您的数据包含NaN?Numpy nan被认为是浮点值

>>> import numpy as np
>>> type(np.nan)
<class 'float'>
Run Code Online (Sandbox Code Playgroud)