title: Conditional numpy.cumsum?
body: <p>I'm very new to python and numpy, so sorry if I misuse some terminology.</p>
  
  <p>I have converted a raster to a 2D numpy array in the hopes of doing calculations on it quickly and efficiently.</p>
  
  <ul>
  <li><p>I need to get the cumulative sum across a numpy array such that, for
  each value, I generate the sum of all values that are less than or
  equal to that, and write that value to a new array.  I need to cycle
  through the entire array that way.</p></li>
  <li><p>I also need to scale the output between 1 and 100, but that seems<br>
  more straightforward.</p></li>
  </ul>
  
  <p>Attempt to clarify by example:</p>
  
  <pre><code>array([[ 4,  1  ,  3   ,  2] dtype=float32)
  </code></pre>
  
  <p>I would want the output values (just doing first row by hand) to read:</p>
  
  <pre><code>array([[ 10,  1  ,  6   ,  3], etc.
  </code></pre>
  
  <p>Any ideas on how to do that?</p>
  
  <p>Thanks in advance!</p>
  
  <hr>
  
  <p>The near finished script for anyone who's interested:</p>
  
  <pre><code>#Generate Cumulative Thresholds
  #5/15/14
  
  import os
  import sys
  import arcpy
  import numpy as np
  
  #Enable overwriting output data
  arcpy.env.overwriteOutput=True
  
  #Set working directory
  os.chdir("E:/NSF Project/Salamander_Data/Continuous_Rasters/Canadian_GCM/2020/A2A/")
  
  #Set geoprocessing variables
  inRaster = "zero_eurycea_cirrigera_CA2A2020.tif"
  des = arcpy.Describe(inRaster)
  sr = des.SpatialReference
  ext = des.Extent
  ll = arcpy.Point(ext.XMin,ext.YMin)
  
  #Convert GeoTIFF to numpy array
  a = arcpy.RasterToNumPyArray(inRaster)
  
  #Flatten for calculations
  a.flatten()
  
  #Find unique values, and record their indices to a separate object
  a_unq, a_inv = np.unique(a, return_inverse=True)
  
  #Count occurences of array indices
  a_cnt = np.bincount(a_inv)
  
  #Cumulatively sum the unique values multiplied by the number of
  #occurences, arrange sums as initial array
  b = np.cumsum(a_unq * a_cnt)[a_inv]
  
  #Divide all values by 10 (reverses earlier multiplication done to
  #facilitate accurate translation of ASCII scientific notation
  #values &lt; 1 to array)
  b /= 10
  
  #Rescale values between 1 and 100
  maxval = np.amax(b)
  b /= maxval
  b *= 100
  
  #Restore flattened array to shape of initial array
  c = b.reshape(a.shape)
  
  #Convert the array back to raster format
  outRaster = arcpy.NumPyArrayToRaster(c,ll,des.meanCellWidth,des.meanCellHeight)
  
  #Set output projection to match input
  arcpy.DefineProjection_management(outRaster, sr)
  
  #Save the raster as a TIFF
  outRaster.save("C:/Users/mkcarte2/Desktop/TestData/outRaster.tif")
  
  sys.exit()
  </code></pre>