首页 > 解决方案 > 如何收集列表并加载到数据框中

问题描述

以下代码创建数据框、标记和过滤停用词。但是,我是否坚持尝试正确收集结果以加载回 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']

标签: pythonpandasdataframe

解决方案


正如您所提到的,您需要一个列表列表才能使分配工作。另一种解决方案是使用您在代码开头使用的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) 

请注意,您不必在分配给它之前创建列。


推荐阅读