I have one dataframe like this with the first column is the index (i.e., index = [1,2,3]):
1 2 3
1 0 0.43 0.61
2 0.88 0 0.12
3 0.33 0.95 0
The new dataframe should look like the below:
Link Value
1_1 0
1_2 0.43
1_3 0.61
2_1 0.88
2_2 0
2_3 0.12
3_1 0.33
3_2 0.95
3_3 0
Any help is highly appreciated! Thank you!
Simply do this
import pandas as pd
data = {
1: [0, 0.43, 0.61],
2: [0.88, 0, 0.12],
3: [0.33, 0.95, 0]
}
index = [1, 2, 3]
df = pd.DataFrame(data, index=index)
df_melted = df.reset_index().melt(id_vars='index', var_name='Column', value_name='Value')
df_melted['Link'] = df_melted['index'].astype(str) + '_' + df_melted['Column'].astype(str)
df_result = df_melted[['Link', 'Value']]
df_result
which gives
Link Value
0 1_1 0.00
1 2_1 0.43
2 3_1 0.61
3 1_2 0.88
4 2_2 0.00
5 3_2 0.12
6 1_3 0.33
7 2_3 0.95
8 3_3 0.00