# How to reclassify a raster into equal intervals in numpy?

I want to reclassify a raster based on equal intervals. For example, if the value is in the first interval, the raster cell should be ouput as 1; the second interval should be a 2, etc. So far I've using this bit of code, which kind of works, but it doesn't handle negative numbers at all (the raster I'm using has a range of -0.4 to 1).

How can I get this working as intended?

``````import rasterio
import numpy as np

def reclass(inRaster, outRaster, mode, classes):
with rasterio.open(inRaster) as src:
profile = src.profile

m_array = np.ma.masked_array(array, array == np.amin(array))
if mode == 'EqualInterval':
amin, amax = np.amin(m_array), np.amax(m_array)
interval = (amax - amin) / classes

for x in range(classes):
if x == 0:
m_array[np.where(m_array < interval)] = x
else:
m_array[np.where((m_array >= (interval * x)) & (m_array <= (interval * (x+1))))] = x

with rasterio.open(outRaster, 'w', **profile) as dst:
# Write to disk
dst.write(array)

reclass(inraster, outraster, 'EqualInterval', 6)
``````

Try `np.linspace()` to create the bins at the specified interval, then `np.digitize()` to return the indices to the appropriate bins (i.e. the class)
``````bins = np.linspace(np.min(m_array), np.max(m_array), num=classes)