I'd like to generate a set of groups based on a boolean OR criterion in pandas. A group consists of members that match on column A OR column B.
For example, in this dataframe:
df = pd.DataFrame([[1,1],[2,2],[2,3],[2,4],[3,3],[4,5]], columns = ['A','B'])
A B
0 1 1
1 2 2
2 2 3
3 2 4
4 3 3
5 4 5
Because rows 1, 2 and 3 match on column A, and 2 and 4 match on column B, I'd like the id values to be:
A B id
0 1 1 0
1 2 2 1
2 2 3 1
3 2 4 1
4 3 3 1
5 4 5 2
I can't find any solution short of creating an NxN scipy graph with the connections, and using scipy.sparse.csgraph.connected_components. Are there any more straightforward options?