如何在 csv 文件的两列中找到重复项,然后将它们合并到 Python 中?
How do I find duplicates within two columns in a csv file, then combine them in Python?
我正在处理一个大型的蛋白质-蛋白质相互作用数据集,我将其保存在一个 .csv 文件中。前两列是相互作用的蛋白质,顺序无关紧要(即 A/B 与 B/A 相同,因此它们是重复的)。还有第三列,其中包含发布这些交互的来源。重复对可以来自相同来源,也可以来自不同来源。
对于来自两个或多个来源的重复项,如何合并它们,然后在第三列中列出一次交互的所有来源? (即对于交互 A/B,重复项为 A/B 和 B/A)。
下面是列的示例:
Interactor A Interactor B Source
A B Mary (2005)
C D John (2004)
B A Mary (2005)
A B Steve (1993)
D C Steve (1993)
在这种情况下,我需要
Interactor A Interactor B Source
A B Mary (2005), Steve (1993)
C D John (2004), Steve (1993)
谢谢!
您可以使用 sorted tuple
作为字典键来聚合它们(要使 A, B
和 B, A
等价,元组可以是用作字典键,因为它是不可变的和可散列的 - 列表不是)。使用 set
存储聚合值并避免重复。
我还要加入 defaultdict
以便更好地聚合值:
from collections import defaultdict
import csv
# ... read values using a csv reader (assuming name csv_reader)
result = defaultdict(set)
for row in csv_reader:
# create same key for `A, B` and `B, A`
key = tuple(sorted([row[0], row[1]]))
result[key].add(row[2])
# result should now contain all aggregated values
我正在处理一个大型的蛋白质-蛋白质相互作用数据集,我将其保存在一个 .csv 文件中。前两列是相互作用的蛋白质,顺序无关紧要(即 A/B 与 B/A 相同,因此它们是重复的)。还有第三列,其中包含发布这些交互的来源。重复对可以来自相同来源,也可以来自不同来源。
对于来自两个或多个来源的重复项,如何合并它们,然后在第三列中列出一次交互的所有来源? (即对于交互 A/B,重复项为 A/B 和 B/A)。
下面是列的示例:
Interactor A Interactor B Source
A B Mary (2005)
C D John (2004)
B A Mary (2005)
A B Steve (1993)
D C Steve (1993)
在这种情况下,我需要
Interactor A Interactor B Source
A B Mary (2005), Steve (1993)
C D John (2004), Steve (1993)
谢谢!
您可以使用 sorted tuple
作为字典键来聚合它们(要使 A, B
和 B, A
等价,元组可以是用作字典键,因为它是不可变的和可散列的 - 列表不是)。使用 set
存储聚合值并避免重复。
我还要加入 defaultdict
以便更好地聚合值:
from collections import defaultdict
import csv
# ... read values using a csv reader (assuming name csv_reader)
result = defaultdict(set)
for row in csv_reader:
# create same key for `A, B` and `B, A`
key = tuple(sorted([row[0], row[1]]))
result[key].add(row[2])
# result should now contain all aggregated values