[英]In Pandas, how to create a unique ID based on the common interrelation of other columns?
I have a dataframe with two IDs columns.我有一个带有两个 ID 列的 dataframe。 I need to set a unique common interrelated ID with te following condition: if either ID1 or ID2 has some of them in common, they must have the same common_ID (ID_3).
我需要使用以下条件设置一个唯一的公共关联 ID:如果 ID1 或 ID2 有一些共同点,则它们必须具有相同的 common_ID (ID_3)。
The dataframe looks like: dataframe 看起来像:
df = pd.DataFrame({'ID_1': ['111', '111', '222', '333', '333', '444', '555', '666', '666', '777'],
'ID_2': ['AAA', 'BBB', 'AAA', 'BBB', 'CCC', 'DDD', 'EEE', 'DDD', 'FFF', 'CCC']})
The desired output should be as follow:所需的 output 应如下所示:
ID_1 ![]() |
ID_2 ![]() |
ID_3 ![]() |
---|---|---|
111 ![]() |
AAA ![]() |
1 ![]() |
111 ![]() |
BBB ![]() |
1 ![]() |
222 ![]() |
AAA ![]() |
1 ![]() |
333 ![]() |
BBB ![]() |
1 ![]() |
333 ![]() |
CCC ![]() |
1 ![]() |
444 ![]() |
DDD ![]() |
2 ![]() |
555 ![]() |
EEE![]() |
3 ![]() |
666 ![]() |
DDD ![]() |
2 ![]() |
666 ![]() |
FFF ![]() |
2 ![]() |
777 ![]() |
CCC ![]() |
1 ![]() |
df_output = pd.DataFrame({'ID_1': ['111', '111', '222', '333', '333', '444', '555', '666', '666', '777'],
'ID_2': ['AAA', 'BBB', 'AAA', 'BBB', 'CCC', 'DDD', 'EEE', 'DDD', 'FFF', 'CCC'],
'ID_3': ['1', '1', '1', '1', '1', '2', '3', '2', '2', '1']})
to clarify the conditions澄清条件
In 1st and 2nd row ID_1 the same, so they must have the same ID_3.在第 1 行和第 2 行 ID_1 相同,因此它们必须具有相同的 ID_3。
The 3rd row has the same ID_2 as 1st row, so its ID_3 must be the same as 1st row = 1.第 3 行的 ID_2 与第 1 行相同,因此其 ID_3 必须与 1st row = 1 相同。
The 4th row has the same ID_2 as 2nd row, that's why it must be set the same ID_3 as 2nd = 1.第 4 行与第 2 行具有相同的 ID_2,这就是为什么必须将其设置为与 2nd = 1 相同的 ID_3。
The 5th row has the same ID_1 as 4th, so ID_3 = 1.第 5 行的 ID_1 与第 4 行相同,因此 ID_3 = 1。
The 6th row has a unique combination of ID_1 and ID_2 at this moment, so it's marked as ID_3 = 2.第 6 行此时有 ID_1 和 ID_2 的唯一组合,因此标记为 ID_3 = 2。
Than 7th row = 3.比第 7 行 = 3。
But 8th has the same ID_2 as 6th, so ID_3 = 2.但是 8th 和 6th 有相同的 ID_2,所以 ID_3 = 2。
and so on等等
I think we can use networkx
to solve this:我认为我们可以使用
networkx
来解决这个问题:
import networkx as nx
G=nx.Graph()
G.add_edges_from(df[['ID_1','ID_2']].to_numpy().tolist())
cc = list(nx.connected_components(G))
L=[dict.fromkeys(b,a) for a, b in enumerate(cc,1)]
d={k: v for d in L for k, v in d.items()}
out = df.assign(ID_3=df['ID_2'].map(d))
print(out)
ID_1 ID_2 ID_3
0 111 AAA 1
1 111 BBB 1
2 222 AAA 1
3 333 BBB 1
4 333 CCC 1
5 444 DDD 2
6 555 EEE 3
7 666 DDD 2
8 666 FFF 2
9 777 CCC 1
To see connected components:要查看连接的组件:
print(cc)
[{'111', '777', '222', 'AAA', '333', 'BBB', 'CCC'},
{'DDD', 'FFF', '666', '444'}, {'555', 'EEE'}]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.