return the total number of neighbors by using pysal's weights object

88 Views Asked by At

I construct a weights object:

import pysal as ps
neighbors = {0: [3, 1], 1: [0, 2, 2], 2: [1, 2], 3: [0, 1, 1]}
weights = {0: [1, 1], 1: [1, 1, 1], 2: [1, 1], 3: [1, 1, 1]}
w = ps.W(neighbors, weights)

Weights object in pysal has a neighbors attribute like the following:

w.neighbors

It will returns a dict: {0: [3, 1], 1: [0, 2, 2], 2: [1, 2], 3: [0, 1, 1]}.

I've checked pysal's api and find lots of methods and attribute to return something about the number of neighbors but not the total number of all neighbors.

For the above w, I want it to return something like: {0: 2, 1: 3, 2: 2, 3: 3}. Instead of looping over the dict like:

n_nbrs = dict()
for key, value in w.neighbors.items():
    n_nbrs[key] = len(value)

Is there any easy way to achieve this?

1

There are 1 best solutions below

0
On BEST ANSWER

You can use w.cardinalities. It will return exactly what are you looking for - {0: 2, 1: 3, 2: 2, 3: 3}.

PySAL is currently changing its structure, so the weights module is now part of libpysal package and its documentation is explaining it, unlike the one you are referring to.