johnny
johnny

Reputation: 11

Building and adjacency matrix from 2 column pandas df

I am attempting to take a 2 column pandas df (where column 1 is node 1, and column 2 is node 2, thus signifying an edge between the nodes) and converting to adjacency matrix. I have followed the following code snippet from SO (Create adjacency matrix for two columns in pandas dataframe), but this does not create a symmetric matrix, which is what I need. It still makes correct dimension, but help would be greatly appreciated:

Data: 2 column df of edges

Code:

df = pd.crosstab(edges_df[0], edges_df[1])

idx = df.columns.union(df.index)

df = df.reindex(index = idx, columns=idx, fill_value=0)

Upvotes: 1

Views: 378

Answers (1)

null
null

Reputation: 2137

Following the example and the answer provided here, you can simply create two crosstabs and merge them like,

Using the example there, and assume we have dataframe as follows:

index  Name_A  Name_B
  0    Adam    Ben
  1    Chris   David
  2    Adam    Chris
  3    Ben     Chris

Code

def get_adjacency_matrix(df, col1, col2):
    df = pd.crosstab(df[col1], df[col2])
    idx = df.columns.union(df.index)
    df = df.reindex(index = idx, columns=idx, fill_value=0)
    return df

a_to_b = get_adjacency_matrix(df, "Name_A", "Name_B")
b_to_a = get_adjacency_matrix(df, "Name_B", "Name_A")

symmetric_adjacency_matrix = a_to_b + b_to_a

Output

       Adam  Ben  Chris  David
Adam      0    1      1      0
Ben       1    0      1      0
Chris     1    1      0      1
David     0    0      1      0

Upvotes: 1

Related Questions