本文介绍了连续二维切片上的Numpy矢量化函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个3D numpy数组.我想通过在沿轴的连续2d切片上执行一个函数并将结果切片堆叠在一起来形成一个新的3d数组.显然,有很多方法可以做到这一点.我想以最简洁的方式做到这一点.我认为使用 numpy.vectorize 可以实现这一点,但是这似乎产生了一个对我数组中的每个值进行迭代的函数,而不是通过沿第一个轴移动获取的2D切片.>

基本上,我想要看起来像这样的代码:

  new3dmat = np.vectorize(func2dmat)(my3dmat) 

并完成与此相同的事情:

  new3dmat = np.empty_like(my3dmat)对于范围内的我(my3dmat.shape [0]):new3dmat [i] = func2dmat(my3dmat [i]) 

我该怎么做?

解决方案

恐怕以下内容是简洁与性能之间的最佳折衷.不幸的是,apply_along_axis不采用多个轴.

  new3dmat = np.array([用于my3dmat中切片的func2dmat(slice)]) 

就额外的分配等而言,这不是理想的选择,但是除非.shape [0]相对于.size较大,否则额外的开销应该很小.

I have a 3D numpy array. I would like to form a new 3d array by executing a function on successive 2d slices along an axis, and stacking the resulting slices together. Clearly there are many ways to do this; I'd like to do it in the most concise way possible. I'd think this would be possible with numpy.vectorize, but this seems to produce a function that iterates over every value in my array, rather than 2D slices taken by moving along the first axis.

Basically, I want code that looks something like this:

new3dmat = np.vectorize(func2dmat)(my3dmat)

And accomplishes the same thing as this:

new3dmat = np.empty_like(my3dmat)
for i in range(my3dmat.shape[0]):
  new3dmat[i] = func2dmat(my3dmat[i])

How can I accomplish this?

解决方案

I am afraid something like below is the best compromise between conciseness and performance. apply_along_axis does not take multiple axes, unfortunately.

new3dmat = np.array([func2dmat(slice) for slice in my3dmat])

It isn't ideal in terms of extra allocations and so on, but unless .shape[0] is big relative to .size, the extra overhead should be minimal.

这篇关于连续二维切片上的Numpy矢量化函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-17 01:02