【发布时间】:2021-09-18 18:18:03
【问题描述】:
我有一个如下所示的熊猫数据框:
df = pd.DataFrame({ 'text':['the weather is nice though', 'How are you today','the beautiful girl and the nice boy']})
df['sentence_number'] = df.index + 1
df['token'] = df['text'].str.split().tolist()
df= df.explode('token').reset_index(drop=True)
我必须有一列用于标记,因为我需要它用于另一个项目。我已将以下内容应用于我的数据框。
import spacy
nlp = spacy.load("en_core_web_sm")
dep_children_sm = []
def dep_children_tagger(txt):
children = [[[child for child in n.children] for n in doc] for doc in nlp.pipe(txt)]
dep_children_sm.append(children)
dep_children_tagger(df.text)
由于必须在句子级别应用 n.children 方法,因此我必须使用文本列而不是标记列,因此输出具有重复列表。我现在想从我的列表 'dep_children_sm' 中删除这些重复,并且我已经完成了以下操作,
children_flattened =[item for sublist in dep_children_sm for item in sublist]
list(k for k,_ in itertools.groupby(children_flattened))
但什么也没发生,我仍然有重复的列表。我也尝试在调用函数时将 drop_duplicates() 添加到文本列,但问题是我的原始数据框中有重复的句子,不幸的是不能这样做。
desired output = [[[], [the], [weather, nice, though], [], []], [[], [How, you, today], [], []], [[], [], [the, beautiful, and, boy], [], [], [], [the, nice]]]
【问题讨论】:
-
目前还不清楚您要做什么。你能提供预期的输出数据框吗?此外,您的代码不可重现,因为
nlp未定义。 -
对不起,我添加了输出和 nlp 信息
-
@mozway,我刚刚意识到问题出在哪里,虽然我不知道如何处理它。问题是 children_flattened 是 nlp.tokens 列表的列表,所以这就是 itertools 方法不起作用的原因。我想如果有办法将列表转换为字符串,它可能会起作用
标签: pandas list nested duplicates flatten