我对 python 和 numpy 很陌生,如果我误用了一些术语,我很抱歉。
我已将栅格转换为 2D numpy 数组,希望能够快速有效地对其进行计算。
我需要在一个 numpy 数组中获取累积总和,以便对于每个值,我生成小于或等于该值的所有值的总和,并将该值写入一个新数组。我需要以这种方式循环遍历整个数组。
我还需要在 1 到 100 之间缩放输出,但这似乎
更简单。
尝试举例说明:
array([[ 4, 1 , 3 , 2] dtype=float32)
我希望输出值(仅手动执行第一行)读取:
array([[ 10, 1 , 6 , 3], etc.
关于如何做到这一点的任何想法?
提前致谢!
对于任何有兴趣的人来说,即将完成的脚本:
#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 < 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()