gpt4 book ai didi

python - 有条件的 numpy.cumsum?

转载 作者:太空狗 更新时间:2023-10-29 20:14:20 24 4
gpt4 key购买 nike

我是 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()

最佳答案

根据您希望如何处理重复,这可能有效:

In [40]: a
Out[40]: array([4, 4, 2, 1, 0, 3, 3, 1, 0, 2])

In [41]: a_unq, a_inv = np.unique(a, return_inverse=True)

In [42]: a_cnt = np.bincount(a_inv)

In [44]: np.cumsum(a_unq * a_cnt)[a_inv]
Out[44]: array([20, 20, 6, 2, 0, 12, 12, 2, 0, 6], dtype=int64)

当然 a 是您的数组展平的位置,然后您必须将其重新整形为原始形状。


当然,一旦 numpy 1.9 发布,您可以更快地将上面的第 41 行和第 42 行压缩为单个行:

a_unq, a_inv, a_cnt = np.unique(a, return_inverse=True, return_counts=True)

关于python - 有条件的 numpy.cumsum?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23662704/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com