Mapping graph/relationship based values in a DataFrame in python

I have an input DataFrame in the below format:

input_data = [[1000, 1002], [1002, 1003], [1004, 1000],[1010,1050],[1060,1002],[1050,1100],[1200,1250],[1300,1200]]
input_df = pd.DataFrame(input_data, columns = ['Value1', 'Value2']) 
print(input_df)

Ignored the index for readability,

Value1  Value2
1000    1002
1002    1003
1004    1000
1010    1050
1060    1002
1050    1100
1200    1250
1300    1200

The output I am expecting is shown below. I need to map all related values (be it value1 -> value2 or value2 -> value1) and collect them all to ordered indexes(starting from 1) like below:

Index Value
1   1000
1   1002
1   1003
1   1004
1   1060
2   1010
2   1050
2   1100
3   1200
3   1250
3   1300
3   1200

What I have tried? I did try looping over the rows in input. I’m able to relate if values in a single row are related. But I’m finding it hard to use this logic when the relationships spans across multiple rows and multiple columns(Value1 and Value2)

Answer

Use convert_matrix.from_pandas_edgelist with connected_components first, then create dictionary for mapping, reshape by DataFrame.melt, map values per groups by Series.map, remove duplicates DataFrame.drop_duplicates and last sorting:

import networkx as nx

# Create the graph from the dataframe
g = nx.Graph()
g = nx.from_pandas_edgelist(input_df,'Value1','Value2')

connected_components = nx.connected_components(g)

# Find the component id of the nodes
node2id = {}
for cid, component in enumerate(connected_components):
    for node in component:
        node2id[node] = cid

df = input_df.melt()
df['g'] = df['value'].map(node2id)
df = df.drop_duplicates(['value','g']).sort_values(['g','value'])
print (df)
   variable  value  g
0    Value1   1000  0
1    Value1   1002  0
9    Value2   1003  0
2    Value1   1004  0
4    Value1   1060  0
3    Value1   1010  1
5    Value1   1050  1
13   Value2   1100  1
6    Value1   1200  2
14   Value2   1250  2
7    Value1   1300  2