I have a 2D numpy array in which each row contains 2 integers. I want to find all the groups of elements belonging to rows which share common elements (a.k.a connected components of a graph from the edgelist array). For example, for the array:
[[ 0 4]
[ 0 7]
[ 1 2]
[ 1 13]
[ 2 1]
[ 2 9]
[ 3 14]
[ 3 16]
[ 4 0]
[ 4 5]
[ 5 4]
[ 5 6]
[ 6 5]
[ 6 7]
[ 7 0]
[ 7 6]]
would contain the groups
[[ 0 4 5 6 7]
[ 1 2 13 9]
[ 3 14 16]]
If you can use libraries, assuming your array is a (Note that you cannot have components as numpy array since they can be non-rectangular array which does not exist in numpy, so this outputs them as sets):
import networkx as nx
G=nx.Graph()
G.add_edges_from(a)
print(sorted(nx.connected_components(G), key = len, reverse=True))
#[{0, 4, 5, 6, 7}, {1, 2, 13, 9}, {16, 3, 14}]
And if you need a pure numpyic solution without extra libraries, please check out this generalized solution: https://stackoverflow.com/a/61764414/4975981
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With