I need to do for loops to adjacency matrix in python. My goal is to find the first and second order of neighbours in matrix. I did the matrix with pysal queen contiguity. 1 is neighbour, 0 isn´t a neighbour.Code:
import pandas as pd
import pysal as ps
w = ps.queen_from_shapefile('test.shp')
Wmatrix, ids = w.full()
Wmatrix
W_DataFrame = pd.DataFrame(Wmatrix,columns=["A","B","C","D","E","F",
"G","H","I","J","K","L",
"N","M"],
index=["A","B","C","D","E","F",
"G","H","I","J","K","L",
"N","M"])
print W_DataFrame
The matrix is:
A B C D E F G H I J K L N M
A 0.0 0.0 1.0 0.0 0.0 0.0 1.0 0.0 0.0 0.0 1.0 0.0 0.0 0.0
B 0.0 0.0 0.0 0.0 1.0 0.0 1.0 0.0 1.0 0.0 0.0 0.0 0.0 0.0
C 1.0 0.0 0.0 1.0 0.0 0.0 0.0 1.0 0.0 1.0 1.0 1.0 0.0 1.0
D 0.0 0.0 1.0 0.0 0.0 0.0 0.0 0.0 0.0 1.0 0.0 0.0 1.0 0.0
E 0.0 1.0 0.0 0.0 0.0 0.0 1.0 0.0 1.0 0.0 1.0 0.0 0.0 0.0
F 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 1.0 0.0 0.0 1.0 0.0
G 1.0 1.0 0.0 0.0 1.0 0.0 0.0 0.0 0.0 0.0 1.0 0.0 0.0 0.0
H 0.0 0.0 1.0 0.0 0.0 0.0 0.0 0.0 1.0 0.0 1.0 1.0 0.0 0.0
I 0.0 1.0 0.0 0.0 1.0 0.0 0.0 1.0 0.0 0.0 1.0 1.0 0.0 0.0
J 0.0 0.0 1.0 1.0 0.0 1.0 0.0 0.0 0.0 0.0 0.0 0.0 1.0 1.0
K 1.0 0.0 1.0 0.0 1.0 0.0 1.0 1.0 1.0 0.0 0.0 0.0 0.0 0.0
L 0.0 0.0 1.0 0.0 0.0 0.0 0.0 1.0 1.0 0.0 0.0 0.0 0.0 1.0
N 0.0 0.0 0.0 1.0 0.0 1.0 0.0 0.0 0.0 1.0 0.0 0.0 0.0 0.0
M 0.0 0.0 1.0 0.0 0.0 0.0 0.0 0.0 0.0 1.0 0.0 1.0 0.0 0.0
For example: Position A have 3 first neighbours (C,H,K) and B is neighbour of G, and C is neighbour of B.
How do I for loops to built a dictionary of lists? Such as: {'A': ['C','H','K','G','B'] }