11

I am attempting to extract natural break values from a raster using Python.

The intended process goes: Arcpy raster object to NumPy Array (using RasterToNumPyArray) to natural break values (using PySAL Natural Breaks function).

import arcpy, pysal
from pysal.esda.mapclassify import Natural_Breaks as nb
# code to create greenIndex arcpy Raster object here
greenArray = arcpy.RasterToNumPyArray(greenIndex)
breaks = nb(greenArray,k=2,initial=20)

This code returns the error, "ValueError: matrix must be 2-dimensional".

As far as I know, greenArray is a 2-dimensional array.

  • 1
    Have you tried checking the greenArray dimensions before trying to process it with Natural_Breaks? Looks like calling .shape on the array will give you the array dimensions. I haven't done any of this before, but this post seems helpful...stackoverflow.com/questions/3061761/numpy-array-dimensions – Branco Sep 25 '14 at 20:20
  • 1
    Thanks, Branco. I did come across that thread, which lead me to believe that my array was 2-dimensional. The return of greenArray.shape = (1536,2048), and greenArray.ndim = 2. I think I've come up with a solution (using numpy.ravel()), which I will write up shortly. – phloem Sep 25 '14 at 20:32
  • 1
    @phloem Looking at the PySAL docco I think you're right with using flatten and ravel; the Natural_Breaks appears to only accept a 1d vector of values (or, a (n, 1) vector). – om_henners Sep 25 '14 at 22:23
6

Thanks for the help, Branco and om_henners.

The answer to my problem appears to be to use numpy.ravel() to change the array produced by arcpy.RasterToNumPy() to a 1D array:

import arcpy, pysal
from pysal.esda.mapclassify import Natural_Breaks as nb
# code to create greenIndex arcpy Raster object here
greenArray = arcpy.RasterToNumPyArray(greenIndex)
breaks = nb(greenArray.ravel(),k=2,initial=20)

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.