【问题标题】:pandas: how to remove duplicates from a deeply nested list of listspandas:如何从深度嵌套的列表中删除重复项
【发布时间】: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


【解决方案1】:

好的,我想出了如何解决这个问题。问题是 nlp.text 输出一个关于 spacy 标记的列表列表,并且由于这个嵌套列表中没有任何字符串,所以 itertools 不起作用。 由于我无法在分析中从文本列中删除重复项,因此我执行了以下操作。

d =[' '.join([str(c) for c in lst]) for lst in children_flattened]
list(set(d))

这会输出一个不包括重复项的字符串列表

# ['[] [How, you, today] [] []',
# '[] [the] [weather, nice, though] [] []',
# '[] [] [the, beautiful, and, boy] [] [] [] [the, nice]']

【讨论】:

    【解决方案2】:

    您似乎想将您的功能应用于独特的文本。因此,您可以首先在 df.text 上使用pandas.Series.unique 方法

    >>> df['text'].unique()
    array(['the weather is nice though', 'How are you today',
           'the beautiful girl and the nice boy'], dtype=object)
    

    然后我会简化你的函数来直接输出结果。不需要全局列表。此外,您的函数正在添加额外级别的列表,这似乎是不需要的。

    def dep_children_tagger(txt):
        return [[[child for child in n.children] for n in doc] for doc in nlp.pipe(txt)]
    

    最后,将你的函数应用于独特的文本:

    dep_children_sm = dep_children_tagger(df['text'].unique())
    

    这给出了:

    >>> dep_children_sm
    [[[], [the], [weather, nice, though], [], []],
     [[], [How, you, today], [], []],
     [[], [], [the, beautiful, and, boy], [], [], [], [the, nice]]]
    

    【讨论】:

    • 感谢您的回复。不幸的是,我不能那样做。我在我的问题中也提到过,我的原始 df 中有一些重复的句子,不幸的是我无法删除重复的句子或得到唯一的句子
    猜你喜欢
    • 1970-01-01
    • 2016-10-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-02-18
    • 1970-01-01
    • 1970-01-01
    • 2023-02-06
    相关资源
    最近更新 更多