对数据集的所有连接节点进行分组 [英] Grouping all connected nodes of a dataset
问题描述
这不是以下内容的重复:
This is not a duplicate of:
注意:pandas 0.23.4 版
Note: pandas ver 0.23.4
假设:数据可以按任何顺序排列.
Assumptions: data can be laid out in any order.
我有一个清单:
L = ['A', 'B', 'C', 'D', 'L', 'M', 'N', 'O']
我也有一个数据框.Col1 和 Col2 有几个关联的列,其中包含我希望保留的相关信息.信息随意,所以我没有填写.
I also have a dataframe. Col1 and Col2 have several associated columns that have related info I wish to keep. The information is arbitrary so I have not filled it in.
Col1 Col2 Col1Info Col2Info Col1moreInfo Col2moreInfo
A B x x x x
B C
D C
L M
M N
N O
我正在尝试为列表中的每个元素执行搜索和分组".例如,如果我们对列表中的元素D"执行搜索,则会返回以下组.
I am trying to perform a 'search and group' for each element of the list. For example, if we performed a search on an element of the list, 'D', the following group would be returned.
To From Col1Info Col2Info Col1moreInfo Col2moreInfo
A B x x x x
B C
D C
我一直在玩 networkx,但它是一个非常复杂的包.
I have been playing around with networkx but it is a very complex package.
推荐答案
您可以使用两列中的值作为边来定义图形,并查找 connected_components
.下面是一种使用 NetworkX
的方法:
You could define a graph using the values from both columns as edges, and look for the connected_components
. Here's a way using NetworkX
:
import networkx as nx
G=nx.Graph()
G.add_edges_from(df.values.tolist())
cc = list(nx.connected_components(G))
# [{'A', 'B', 'C', 'D'}, {'L', 'M', 'N', 'O'}]
现在假设你想通过 D
过滤,你可以这样做:
Now say for instance you want to filter by D
, you could then do:
component = next(i for i in cc if 'B' in i)
# {'A', 'B', 'C', 'D'}
并索引来自两列的值都在component
中的数据框:
And index the dataframe where the values from both columns are in component
:
df[df.isin(component).all(1)]
Col1 Col2
0 A B
1 B C
2 D C
<小时>
通过生成数据框列表,上述内容可以扩展到列表中的所有项目.然后我们只需使用给定项目在 L
中的位置进行索引:
L = ['A', 'B', 'C', 'D', 'L', 'M', 'N', 'O']
dfs = [df[df.isin(i).all(1)] for j in L for i in cc if j in i]
print(dfs[L.index('D')])
Col1 Col2
0 A B
1 B C
2 D C
print(dfs[L.index('L')])
Col1 Col2
3 L M
4 M N
5 N O
这篇关于对数据集的所有连接节点进行分组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!