I would like to apply Moran's I spatial auto-correlation measure to 2D arrays or raster files in Python and I am wondering if there is an available implementation for it.

I know Pysal offers an implementation but I was not able to figure how to apply it to 2D data.

Any other libraries/implementations that would allow me to do that?

2 Answers 2


Eventually, with the help of Serge Rey's answer and this link in the documentation, I ended up using pysal's implementation as follows:

import pysal as ps
w = ps.lat2W(input_img.shape[0],input_img.shape[1], rook=False, id_type="int")
lm = ps.Moran_Local(input_img,w)
moran_significance = np.reshape(lm.p_sim, input_img.shape)

In the last line I reshape the array of pseudo p_values (which indicate the significance of the local indicators of spatial association (LISAs) ) for visualization purposes:

enter image description here

I just leave it here as an answer in case someone finds it useful in the future.

  • Very cool! Can you just clarify the input_img data type and how to create it?
    – nealmcb
    Commented Feb 11, 2019 at 15:19

If the raster has r rows and c columns, then you can create a pysal W object with:

w = pysal.lat2W(r,c)

and use that with the Moran class.

More details available at: https://pysal.org/libpysal/generated/libpysal.weights.lat2W.html#libpysal.weights.lat2W

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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