在python中去除重複行的資料框

2024-04-20 07:15:34 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个数据帧,它有27949行和7列,前几行如下所示 https://i.stack.imgur.com/1Pipf.png

任务: 在dataframe中,我有一个'title'列,其中有许多重复的标题,我想删除这些标题(重复标题:几乎所有标题相同,只有一个或两个单词)。 伪代码: 我想检查第一行与所有其他行&如果其中任何一行是重复的,我想删除它。然后我要检查第二行与所有其他行&如果其中任何一行重复,我要将其删除-与所有行类似,即I=1st line to last line j=I+1 to last line。 我的代码:

for i in range(0,27950):
    for j in range(1,27950):
        a = data_sorted['title'].iloc[i].split()
        b = data_sorted['title'].iloc[j].split()
        if len(a)-len(b)<=2:
            data_sorted.drop(b)
            j=j
        else:
            j+=1
    i+=1

错误: 索引器错误:单个位置索引器超出界限

有人能帮我把代码写出来吗。 提前谢谢。你知道吗


Tags: to代码in标题fordatalentitle
1条回答
网友
1楼 · 发布于 2024-04-20 07:15:34

我建议采取以下办法:

建立一个标题的差异矩阵,其中i,j元素将表示i'th和j'th标题之间的单词差异。你知道吗

像这样:

    import numpy as np
    from itertools import product

    l = list(data_sorted['title'])

    def diff_words(text_1, text_2):
        # return the number of different words between two texts
        words_1 = text_1.split()
        words_2 = text_2.split()
        diff = max(len(words_1),len(words_2))-len(np.intersect1d(words_1, words_2))
        return diff


    differences = [diff_words(i,j) for i,j in product(l,l)]
    # differences: a flat matrix integers where the i,j element is the word difference between titles i and j

相关问题 更多 >