Python NumPy阵列切片索引的确定问题
我有一个Python NumPy阵列切片索引的确定问题,python,arrays,numpy,slice,Python,Arrays,Numpy,Slice,我有一个X*Y元素的NumPy数组,表示为扁平数组(arr=np.array(X*Y)) 给定以下值: X = 832 Y = 961 我需要按以下顺序访问数组的元素: arr[0:832:2] arr[1:832:2] arr[832:1664:2] arr[833:1664:2] ... arr[((Y-1) * X):(X * Y):2] 从数学上讲,我不确定如何为循环中的每个迭代实现开始和停止。对于对此解决方案感兴趣的任何人(每次迭代,不增加每次迭代的移位): 假设您有一个shape
X*Y
元素的NumPy数组,表示为扁平数组(arr=np.array(X*Y)
)
给定以下值:
X = 832
Y = 961
我需要按以下顺序访问数组的元素:
arr[0:832:2]
arr[1:832:2]
arr[832:1664:2]
arr[833:1664:2]
...
arr[((Y-1) * X):(X * Y):2]
从数学上讲,我不确定如何为循环中的每个迭代实现
开始
和停止
。对于对此解决方案感兴趣的任何人(每次迭代,不增加每次迭代的移位):
假设您有一个shape
(x*y,)
数组,您希望将其处理为x
块。您只需将数组重塑为(y,x)
,然后处理行:
>>> x = 832
>>> y = 961
>>> arr = np.arange(x * y)
现在重塑,批量加工。在下面的示例中,我取每行的平均值。可以通过以下方式将任何函数应用于整个阵列:
>>> arr = arr.reshape(y, x)
>>> np.mean(arr[:, ::2], axis=1)
>>> np.mean(arr[:, 1::2], axis=1)
重塑操作不会改变阵列中的数据。它指向的缓冲区与原始缓冲区相同。您可以通过在阵列上调用
ravel
来反转整形。在for循环中使用Y*2
。当您使用Y
时,它只运行到399360
@RamHarnish为什么?我只需要迭代Y
。根据你的问题,最后一个术语应该是(Y-1)*X),(X*Y):2
,也就是798720:799552
,但是你的循环以399360:400192:2
结束。这是一个X-Y问题。您几乎不需要直接在numpy数组中循环。如果你展示你试图对每个区块做什么,我可以改进我的答案。@Mad物理学家我不是循环数组,我是循环一组X和Y值,并在给定的[start:stop:step]
处插入值,例如arr[1:832:2]=4
。你能展示你实际在做什么吗?我仍然认为这是一个x-y问题,因为您的目标是访问数组的元素。为什么?@MadPhysicast脚本位于完全不同的机器(分离的网络)上,因此我无法复制和粘贴,而不愿引入打字错误。也就是说,arr
是表示六边形细分的结构化数组arr
的形状为(X*Y,)
,每个元素的形状为(7,2)
。我正在迭代Y
(列)范围,以便为细分分配值,因为每列共享x轴值。请查看我的答案,看看是否有帮助
This should do the trick
Y = 961
X = 832
all_ = np.random.rand(832*961)
# Iterating over the values of y
for i in range(1,Y):
# getting the indicies from the array we need
# i - 1 = Start
# X*i = END
# 2 is the step
indicies = list(range(i-1,X*i,2))
# np.take slice values from the array or get values corresponding to the list of indicies we prepared above
required_array = np.take(indices=indices)
This should do the trick
Y = 961
X = 832
all_ = np.random.rand(832*961)
# Iterating over the values of y
for i in range(1,Y):
# getting the indicies from the array we need
# i - 1 = Start
# X*i = END
# 2 is the step
indicies = list(range(i-1,X*i,2))
# np.take slice values from the array or get values corresponding to the list of indicies we prepared above
required_array = np.take(indices=indices)