python - 如何收集列表并加载到数据框中
问题描述
以下代码创建数据框、标记和过滤停用词。但是,我是否坚持尝试正确收集结果以加载回 dataframe 的列中。尝试将结果放回数据框中(使用注释代码)会产生以下错误ValueError: Length of values does not match length of index
。似乎问题在于我如何将列表加载回df。我认为这是一次治疗他们。我不清楚如何形成列表列表,这是我认为需要的。既不合适append()
也extend()
不合适,或者如果它们是我做的不正确。任何见解将不胜感激。
最小的例子
# Load libraries
import numpy as np
import pandas as pd
import spacy
# Create dataframe and tokenize
df = pd.DataFrame({'Text': ['This is the first text. It is two sentences',
'This is the second text, with one sentence']})
nlp = spacy.load("en_core_web_sm")
df['Tokens'] = ''
doc = df['Text']
doc = doc.apply(lambda x: nlp(x))
df['Tokens'] = doc
# df # check dataframe
# Filter stopwords
df['No Stop'] = ''
def test_loc(df):
for i in df.index:
doc = df.loc[i,'Tokens']
tokens_no_stop = [token.text for token in doc if not token.is_stop]
print(tokens_no_stop)
# df['No Stop'] = tokens_no_stop # THIS PRODUCES AN ERROR
test_loc(df)
结果
['text', '.', 'sentences']
['second', 'text', ',', 'sentence']
解决方案
正如您所提到的,您需要一个列表列表才能使分配工作。另一种解决方案是使用您在代码开头使用的pandas.apply 。
import numpy as np
import pandas as pd
import spacy
df = pd.DataFrame({'Text': ['This is the first text. It is two sentences',
'This is the second text, with one sentence']})
nlp = spacy.load("en_core_web_sm")
df['Tokens'] = df['Text'].apply(lambda x: nlp(x))
def remove_stop_words(tokens):
return [token.text for token in tokens if not token.is_stop]
df['No Stop'] = df['Tokens'].apply(remove_stop_words)
请注意,您不必在分配给它之前创建列。
推荐阅读
- php - FOSUserBundle - 成功认证时会话中的事件集变量?
- java - Whatsapp Intent:多张图片,每张都有不同的标题
- java - 如何创建整数变量的实例?
- python - 根据上传的文件生成并保存哈希
- django - PermissionError: [Errno 13] Permission denied: '/app/manage.py' 尝试使用 docker-compose 创建项目时
- javascript - grafana 面板间通信
- c++ - 函数上的“未定义符号”错误
- python - For循环跳过某些文件夹
- mysql - 在单个查询中组合 2 个更新查询 - 性能
- json - Laravel 的最大函数嵌套级别“256”达到