Convert Pandas data frame to a list of tuples containing IDs and a weight

Viewed 66

I have a data frame (called df) which is currently formatted like so:

    1      2     3
1   1      0.26  0.02
2   0.26   1     0.61
3   0.02   0.61  1

The IDs are connected by a value and I would like to somehow extract all unique ID values in order to have a more efficient way to add them to my graph on networkx.

The output should look like something like this:

ed_list = [(1,2,{'weight': 0.26}),(1,3,{'weight': 0.02}),(2,3,{'weight':0.61})]

At the moment I use the following method:

# Create matrix 
new_ = df.values
A_d = np.matrix(new_)
G = nx.from_numpy_matrix(A_d) 

I'm wondering if it would be easier/more efficient to create a List of tuples from my df that I could use to connect my nodes, where I could then add edges like so:

G.add_edges_from(ed_list)

EDIT: I have made a mistake in the previous version of my question - the column and row names are just integers

1 Answers

Can you try:

# this s is what you are looking for
s = df.where(df.index.values > df.columns.values[:,None]).stack().reset_index(name='weight')

# we can use dataframe directly
G = nx.from_pandas_edgelist(s,source='level_0',target='level_1', edge_attr='weight')

Or even simpler:

G = nx.from_pandas_adjacency(df)
Related