在POS标签列表的字符串上应用literal_eval会得到ValueError



在pandas列中,我将POS标记列表作为字符串。我想这一定是字符串,因为print(dataset['text_posTagged'][0][0])打印[

数据集['ext_posTagged']

['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:格式错误的节点或字符串:nan

当我在一个有单词列表的列中应用同样的方法时,效果很好。

数据集['text']

['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有什么问题如何正确地做?

只分析非空行。您可以丢弃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'])

最新更新