If I have a dataset in a csv that looks like the one shown below.

How do I convert this into a laplacian matrix using Python?

enter image description here


Use SciPy's Laplacian function:

import numpy as np
from scipy.sparse.csgraph import laplacian

g = np.array([[1, 0, 0, 0],
              [0, 1, 0, 1],
              [0, 0, 0, 1],
              [0, 1, 1, 1]])

|improve this answer|||||

Well the Laplacian matrix is achieved by:

$degree (v_i) $ for $\space$ i=j

$-1$ for $\space$ if $v_j$ and $v_i$ are not adjacent to each other

$0$ otherwise

First, you need to store your file to a 2d-array Then you need to define another 2d-array matrix the same size of your first matrix. Then loop over the elements to fill the Laplacian matrix

import pandas as pd
data = pd.read_csv('data.csv')
df = pd.Dataframe(data)
M = df.as_matrix()
L = np.zeros(df.shape[0], df.shape[1]) #shape[0] and shape[1] should be equal

Then for each element $A_{i,j}$ we calculate their corresponding value in L

for i in range(len(df.shape[0])):
    for j in range(len(df.shape[0])): # or shape[1]
        if M[i][j] == 0 and M[j][i]== 0:
            L[i][j] = -1
        if i == j:
            L[i][j] = sum(M[i][:])
            L[i][j] = 0

I haven't tried the code so consider it much like a pseudo-code.

|improve this answer|||||

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.