python - 对 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 有什么问题?如何正确地做到这一点?
解决方案
仅解析非空行。您可以删除 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'])
推荐阅读
- mysql - 从 Mysql 中获取行并使用 Django 将其显示在 html 中
- c# - T-SQL ... 表示法
- python - python - pandas,如何减少具有相同值的行数据框?
- python - JSONEncoder subclassing went wrong
- laravel - 这段代码在 RedirectIfAuthenticated.php 中是什么意思?
- c++ - 如何找出是否 n! 可以表示为三个连续数的乘积吗?
- apache-camel - jboss eap fuse 7上camel wildfly/undertow集成的奇怪行为-这是错误还是我使用错误?
- c - 如何在没有编译器警告的情况下比较 C 中的补码?
- python-3.x - uWSGI 不会切换到自定义 uwsgi.ini 文件中定义的用户 uid=my_user
- php - 下拉列表中从 db 加载的选项值