python未知长度数组,python – 从具有未知维数的numpy数组中提取超立方体块

我有一些

python代码,目前使用二维数组进行硬连接,如下所示:

import numpy as np

data = np.random.rand(5, 5)

width = 3

for y in range(0, data.shape[1] - W + 1):

for x in range(0, data.shape[0] - W + 1):

block = data[x:x+W, y:y+W]

# Do something with this block

现在,这是一个二维数组的硬编码,我想将其扩展到3D和4D数组.当然,我可以为其他维度编写更多函数,但我想知道是否有一个python / numpy技巧来生成这些子块而不必为多维数据复制此函数.

最佳答案 这是我对这个问题的嘲笑.下面代码背后的想法是找到每个数据片段的“起始索引”.因此,对于5x5x5阵列的4x4x4子阵列,起始索引将是(0,0,0),(0,0,1),(0,1,0),(0,1,1),(1 ,0,0),(1,0,1),(1,1,1),沿每个维度的切片长度为4.

要获取子数组,您只需迭代切片对象的不同元组并将它们传递给数组.

import numpy as np

from itertools import product

def iterslice(data_shape, width):

# check for invalid width

assert(all(sh>=width for sh in data_shape),

'all axes lengths must be at least equal to width')

# gather all allowed starting indices for the data shape

start_indices = [range(sh-width+1) for sh in data_shape]

# create tuples of all allowed starting indices

start_coords = product(*start_indices)

# iterate over tuples of slice objects that have the same dimension

# as data_shape, to be passed to the vector

for start_coord in start_coords:

yield tuple(slice(coord, coord+width) for coord in start_coord)

# create 5x5x5 array

arr = np.arange(0,5**3).reshape(5,5,5)

# create the data slice tuple iterator for 3x3x3 sub-arrays

data_slices = iterslice(arr.shape, 3)

# the sub-arrays are a list of 3x3x3 arrays, in this case

sub_arrays = [arr[ds] for ds in data_slices]

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值