[英]How to chain values and find groups in Pandas
我有一個來自Dataframe
的 Dataframe:
import pandas as pd
df = pd.DataFrame([{'element_from':'A', 'element_to':'B'},
{'element_from':'A', 'element_to':'C'},
{'element_from':'D','element_to':'C'},
{'element_from':'G','element_to':'H'},
{'element_from':'H','element_to':'I'}])
print(df)
Output:
element_from element_to
0 A B
1 A C
2 D C
3 G H
4 H I
它表示不同元素之間的聯系。 由於中介,元素可以間接鏈接。 例如,由於 B,A 和 C 被鏈接。
換句話說,會有我想識別的元素組。
結果可能是一個標識組的新列,如下所示:
element_from element_to group
0 A B G1
1 A C G1
2 D C G1
3 G H G2
4 H I G2
有沒有一種簡單的方法可以在 Pandas 中實現這一目標? 謝謝你。
你可以使用networkx
import networkx as nx
G = nx.Graph()
G.add_nodes_from(df.element_from.append(df.element_to).unique())
G.add_edges_from(df.to_records(False))
groups = list(nx.algorithms.components.connected_components(G))
df["group"] = [groups.index(group) for element in df.element_from for group in groups if element in group]
Output
element_from element_to group
0 A B 0
1 A C 0
2 D C 0
3 G H 1
4 H I 1
要獲得預期的 output,請添加以下行:
df["group"] = 'G' + (df["group"] + 1).astype(str)
element_from element_to group
0 A B G1
1 A C G1
2 D C G1
3 G H G2
4 H I G2
檢查 networkx 和連接的組件。
import networkx as nx
# create graph from edge list
G = nx.from_pandas_edgelist(df, source='element_from', target='element_to')
# find connected components and label the nodes
to_map = {x: f'G{k}' for k,v in enumerate(nx.connected_components(G), 1)
for x in v
}
Output;
element_from element_to group
0 A B G1
1 A C G1
2 D C G1
3 G H G2
4 H I G2
df['group'] = df['element_from'].map(to_map)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.