首页 > 解决方案 > 对 POS 标签列表的字符串应用 literal_eval 会产生 ValueError

问题描述

在 pandas 列中,我将 POS 标签列表作为字符串。我认为这必须是字符串,因为print(dataset['text_posTagged'][0][0])prints [

数据集['text_postTagged']

['VBP', 'JJ', 'NNS', 'VBP', 'JJ', 'IN', 'PRP', 'VBP', 'TO', 'VB', 'PRP', 'RB', 'VBZ', 'DT', 'JJ', 'PRP$', 'NN', 'NN', 'NN', 'NN', 'VBZ', 'JJ']
['UH', 'DT', 'VB', 'VB', 'PRP$', 'NN', 'TO', 'JJ', 'IN', 'PRP', 'MD', 'VB', 'DT', 'VBZ', 'DT', 'NN', 'NN']
['NN', 'VBD', 'NN', 'NN', 'NN', 'DT', 'IN', 'IN', 'NN', 'IN', 'NN', 'NN', 'VBD', 'IN', 'JJ', 'NN', 'NN']

要将其转换为实际列表,我使用了以下内容。

dataset['text_posTagged'] = dataset.text_posTagged.apply(lambda x: literal_eval(x)). 

但是,这给出了ValueError: malformed node or string: nan

当我在具有单词列表的列中应用相同的内容时,它工作正常。

数据集['文本']

['are', 'red', 'violets', 'are', 'blue', 'if', 'you', 'want', 'to', 'buy', 'us', 'here', 'is', 'a', 'clue', 'our', 'eye', 'amp', 'cheek', 'palette', 'is', 'al']
['is', 'it', 'too', 'late', 'now', 'to', 'say', 'sorry']
['our', 'amazonian', 'clay', 'full', 'coverage', 'foundation', 'comes', 'in', '40', 'shades', 'of', 'creamy', 'goodness']

以下打印are

dataset['text'] = dataset.text.apply(lambda x: literal_eval(x)).
print(dataset['text'][0][0])

在 POS 标签列表上应用 literal_eval 有什么问题?如何正确地做到这一点?

标签: pythonpandasnlp

解决方案


仅解析非空行。您可以删除 lambda。

m = dataset['text_posTagged'].notna()
dataset.loc[m, 'text_posTagged'] = (
    dataset.loc[m, 'text_posTagged'].apply(literal_eval))

如果您有 100 行或更少,您还可以使用pd.eval

dataset.loc[m, 'text_posTagged'] = pd.eval(dataset.loc[m, 'text_posTagged'])

推荐阅读