比较表中一行与所有其他行的值

2024-10-01 09:26:56 发布

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

我想使用pandas将单行中的特定列值与所有其他行中的值进行比较。我创建了下面的循环,但由于我的数据帧包含abt 400000行,执行它需要花费很长时间 是否有更智能/更快的方法来执行此操作 对不起,我的python不是很流利,我更习惯用.NET语言编写代码

我的数据框看起来像这样:

    NAME            PROFILE URL             Final Addres
0   ProfileA    appexample.co/userxyz       http://example.com
1   ProfileB    appexample.co/userxyz_1     http://example.com  
2   ProfileC    appexample.co/userabc       http://anotherexample.com
3   ProfileD    appexample.co/userabc_3     http://anotherexample.com
4   ProfileE    appexample.co/userjyl       http://example123.com


在本例中,我试图识别重复的(配置文件)(配置文件A和配置文件B)和;(ProfileC&;ProfileD)是重复的,因为: 1.具有相同的配置文件url(例如,用户位于用户和用户1中) 2.有相同的最终地址

当前代码正在使用:

possible_dup = []
    for row in test.iterrows():
    first = str(row[1]['PROFILE URL'])
    first_url = str(row[1]['Final Address'])
    for sec_row in test.iterrows():
        second = str(sec_row[1]['PROFILE URL'])
        second_url = str(sec_row[1]['Final Address'])
        if (row[1]['PROFILE URL'] == sec_row[1]['PROFILE URL']) :
            continue
        if ((first in second) and (first_url == second_url)):
            dup = '{} , {}'.format(first,second)
            possible_dup.append(dup)

运行时间超过24小时,并且仍在运行,我正在使用jupyter笔记本


Tags: comhttpurl配置文件secprofilefinalrow
2条回答

检查一下duplicated()方法。从文档中:

Return boolean Series denoting duplicate rows.

特别有用的是仅选择列子集的可选参数。根据您的具体目标,您可以使用duplicated()方法做几件事:

要识别重复的行,您需要使用

duplicates = test.duplicated(subset = ['PROFILE URL', 'FINAL Addres'], keep = False)

要识别您将使用的所有重复用户

    duplicate_users = test[test.duplicated(subset = ['PROFILE URL', 'FINAL Addres'], keep = First)]

要返回不带副本的数据帧(以前的每个副本现在只存在一次):

duplicates = test.duplicated(subset = ['PROFILE URL', 'FINAL Addres'])
duplicate_free_df = test.loc[~duplicates]

duplicated()keep参数一起使用为False,这允许我们识别所有重复项

df2 = df[df.duplicated(subset=['Final Addres'],keep=False)]

print(df2)


       NAME              PROFILE URL               Final Addres
0  ProfileA    appexample.co/userxyz         http://example.com
1  ProfileB  appexample.co/userxyz_1         http://example.com
2  ProfileC    appexample.co/userabc  http://anotherexample.com
3  ProfileD  appexample.co/userabc_3  http://anotherexample.com

相关问题 更多 >