【问题标题】:List unique ID's with duplicate values in other columns列出其他列中具有重复值的唯一 ID
【发布时间】:2020-11-15 02:06:01
【问题描述】:

我在 pyodbc 和 python 中使用 SQL 服务器。我想创建一个列表、字典或 panda df 等的列表,其中包含在多列中具有重复值的行的唯一 ID。例如。我有一张这样的桌子:

 ID          size      page       rate
12345         6         12         20  
67890         6         12         20
23456         4         10         15
87654         4         10         15
43210         4         10         15
....

第 1-2 行和第 3-5 行的列大小、页数和比率重复。所以我需要像这样将 ID 组合在一起:(例如列表列表:)

duplicates = [[12345, 67890], [23456, 87654, 43210],...] 

在我的光标执行后,我得到第一个表作为结果:

duplicates =[]
row1 = [row[1] for row in cursor]
row2 = [row[1] for row in cursor]
counter = 1
index = 0
for row in cursor:
   if index <= len(row1)-2:
    n0 = row1[index]
    n1 = row2[index]
    n2 = row1[index+1]
    n3 = row2[index+1]
    if n0 == n1 and n2 == n3:
        duplicates.append(row[0])
    else:
        counter+=1
    index+=1
else: break 

不工作,但任何帮助和指导将不胜感激!谢谢!

【问题讨论】:

  • 参考这篇文章从SQL阅读,然后是df.groupby(['size','page','rate'])['ID'].apply(list).tolist()

标签: python pandas duplicates unique


【解决方案1】:

您可以将查询结果转换为 pandas 数据框(假设名称为“df”)。之后,您可以使用以下行提取重复的 id。

df1 = df.groupby('size')['ID'].apply(list).reset_index(name='duplicates')

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-21
    • 2017-04-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多