在几个方面numpy的卷 [英] Numpy roll in several dimensions
问题描述
我需要一个3D阵列位移的3D矢量算法转变。
截至目前我使用这个(admitedly非常难看)方法:
I need to shift a 3D array by a 3D vector of displacement for an algorithm. As of now I'm using this (admitedly very ugly) method :
shiftedArray = np.roll(np.roll(np.roll(arrayToShift, shift[0], axis=0)
, shift[1], axis=1),
shift[2], axis=2)
其中的作品,而是指我打电话3卷! (我的算法时的58%都花在这些,根据我的分析)
Which works, but means I'm calling 3 rolls ! (58% of my algorithm time is spent in these, according to my profiling)
从Numpy.roll的文档:
From the docs of Numpy.roll:
参数:结果
转变:INT
Parameters:
shift : int
轴:INT,可选
类似数组的参数...所以我不能有一个多维滚动?没有提及
No mention of array-like in parameter ... So I can't have a multidimensional rolling ?
我想我可能只是调用这种功能(听起来像一个numpy的事):
I thought I could just call a this kind of function (sounds like a Numpy thing to do) :
np.roll(arrayToShift,3DshiftVector,axis=(0,1,2))
也许与我的数组的平铺版本重塑?但我怎么计算转移载体?并且这种转变真的一样吗?
Maybe with a flattened version of my array reshaped ? but then how do I compute the shift vector ? and is this shift really the same ?
我很惊讶地发现,这个不容易解决,因为我认为这将是做pretty常见的事(好吧,不是的是的常见的,但...)
I'm surprised to find no easy solution for this, as I thought this would be a pretty common thing to do (okay, not that common, but ...)
那么,如何才能有效地--relatively--由n维向量转移一个ndarray?
So how do we --relatively-- efficiently shift a ndarray by a N-Dimensional vector ?
推荐答案
我觉得 scipy.ndimage.interpolation.shift
会做你想要什么,从<一个href=\"http://docs.scipy.org/doc/scipy-0.15.1/reference/generated/scipy.ndimage.interpolation.shift.html\"相对=nofollow>文档
I think scipy.ndimage.interpolation.shift
will do what you want, from the docs
转变:float或序列,可选的
shift : float or sequence, optional
沿轴的转变。如果浮子,移位是每个轴是相同的。如果一个序列,换挡应包含每个轴一个值。
The shift along the axes. If a float, shift is the same for each axis. If a sequence, shift should contain one value for each axis.
这意味着你可以做到以下几点,
Which means you can do the following,
from scipy.ndimage.interpolation import shift
import numpy as np
arrayToShift = np.reshape([i for i in range(27)],(3,3,3))
print('Before shift')
print(arrayToShift)
shiftVector = (1,2,3)
shiftedarray = shift(arrayToShift,shift=shiftVector,mode='wrap')
print('After shift')
print(shiftedarray)
其中产量,
Before shift
[[[ 0 1 2]
[ 3 4 5]
[ 6 7 8]]
[[ 9 10 11]
[12 13 14]
[15 16 17]]
[[18 19 20]
[21 22 23]
[24 25 26]]]
After shift
[[[16 17 16]
[13 14 13]
[10 11 10]]
[[ 7 8 7]
[ 4 5 4]
[ 1 2 1]]
[[16 17 16]
[13 14 13]
[10 11 10]]]
这篇关于在几个方面numpy的卷的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!