我想'剪切'一个numpy阵列。我不确定我是否正确使用“剪切”一词;通过剪切,我的意思是:
将第一列移动0位置
将第二列移动1个位置
将第三列移动2个位置
等...
所以这个数组:
array([[11, 12, 13],
[17, 18, 19],
[35, 36, 37]])
会变成这个数组:
array([[11, 36, 19],
[17, 12, 37],
[35, 18, 13]])
或类似这样的数组:
array([[11, 0, 0],
[17, 12, 0],
[35, 18, 13]])
取决于我们如何处理边缘。我对边缘行为并不太了解。
这是我尝试执行此功能的函数:
import numpy
def shear(a, strength=1, shift_axis=0, increase_axis=1, edges='clip'):
strength = int(strength)
shift_axis = int(shift_axis)
increase_axis = int(increase_axis)
if shift_axis == increase_axis:
raise UserWarning("Shear can't shift in the direction it increases")
temp = numpy.zeros(a.shape, dtype=int)
indices = []
for d, num in enumerate(a.shape):
coords = numpy.arange(num)
shape = [1] * len(a.shape)
shape[d] = num
coords = coords.reshape(shape) + temp
indices.append(coords)
indices[shift_axis] -= strength * indices[increase_axis]
if edges == 'clip':
indices[shift_axis][indices[shift_axis] < 0] = -1
indices[shift_axis][indices[shift_axis] >= a.shape[shift_axis]] = -1
res = a[indices]
res[indices[shift_axis] == -1] = 0
elif edges == 'roll':
indices[shift_axis] %= a.shape[shift_axis]
res = a[indices]
return res
if __name__ == '__main__':
a = numpy.random.random((3,4))
print a
print shear(a)
似乎有效。如果没有,请告诉我!
它看起来也很笨重而且不优雅。我是否会忽略内置的numpy / scipy功能呢?在numpy中有更清洁/更好/更有效的方法吗?我重新发明了轮子吗?
编辑:
如果这适用于N维数组,而不仅仅是2D情况,则可获得奖励积分。
这个函数将位于循环的中心,我将在数据处理中重复多次,所以我怀疑它实际上值得优化。
第二次编辑: 我终于做了一些基准测试。尽管有循环,看起来像numpy.roll是要走的路。谢谢,tom10和Sven Marnach!
基准测试代码:(在Windows上运行,我认为不要在Linux上使用time.clock)
import time, numpy
def shear_1(a, strength=1, shift_axis=0, increase_axis=1, edges='roll'):
strength = int(strength)
shift_axis = int(shift_axis)
increase_axis = int(increase_axis)
if shift_axis == increase_axis:
raise UserWarning("Shear can't shift in the direction it increases")
temp = numpy.zeros(a.shape, dtype=int)
indices = []
for d, num in enumerate(a.shape):
coords = numpy.arange(num)
shape = [1] * len(a.shape)
shape[d] = num
coords = coords.reshape(shape) + temp
indices.append(coords)
indices[shift_axis] -= strength * indices[increase_axis]
if edges == 'clip':
indices[shift_axis][indices[shift_axis] < 0] = -1
indices[shift_axis][indices[shift_axis] >= a.shape[shift_axis]] = -1
res = a[indices]
res[indices[shift_axis] == -1] = 0
elif edges == 'roll':
indices[shift_axis] %= a.shape[shift_axis]
res = a[indices]
return res
def shear_2(a, strength=1, shift_axis=0, increase_axis=1, edges='roll'):
indices = numpy.indices(a.shape)
indices[shift_axis] -= strength * indices[increase_axis]
indices[shift_axis] %= a.shape[shift_axis]
res = a[tuple(indices)]
if edges == 'clip':
res[indices[shift_axis] < 0] = 0
res[indices[shift_axis] >= a.shape[shift_axis]] = 0
return res
def shear_3(a, strength=1, shift_axis=0, increase_axis=1):
if shift_axis > increase_axis:
shift_axis -= 1
res = numpy.empty_like(a)
index = numpy.index_exp[:] * increase_axis
roll = numpy.roll
for i in range(0, a.shape[increase_axis]):
index_i = index + (i,)
res[index_i] = roll(a[index_i], i * strength, shift_axis)
return res
numpy.random.seed(0)
for a in (
numpy.random.random((3, 3, 3, 3)),
numpy.random.random((50, 50, 50, 50)),
numpy.random.random((300, 300, 10, 10)),
):
print 'Array dimensions:', a.shape
for sa, ia in ((0, 1), (1, 0), (2, 3), (0, 3)):
print 'Shift axis:', sa
print 'Increase axis:', ia
ref = shear_1(a, shift_axis=sa, increase_axis=ia)
for shear, label in ((shear_1, '1'), (shear_2, '2'), (shear_3, '3')):
start = time.clock()
b = shear(a, shift_axis=sa, increase_axis=ia)
end = time.clock()
print label + ': %0.6f seconds'%(end-start)
if (b - ref).max() > 1e-9:
print "Something's wrong."
print
答案 0 :(得分:7)
这可以使用this answer by Joe Kington中描述的技巧来完成:
from numpy.lib.stride_tricks import as_strided
a = numpy.array([[11, 12, 13],
[17, 18, 19],
[35, 36, 37]])
shift_axis = 0
increase_axis = 1
b = numpy.vstack((a, a))
strides = list(b.strides)
strides[increase_axis] -= strides[shift_axis]
strides = (b.strides[0], b.strides[1] - b.strides[0])
as_strided(b, shape=b.shape, strides=strides)[a.shape[0]:]
# array([[11, 36, 19],
# [17, 12, 37],
# [35, 18, 13]])
要获取“剪辑”而不是“滚动”,请使用
b = numpy.vstack((numpy.zeros(a.shape, int), a))
这可能是最有效的方法,因为它根本不使用任何Python循环。
答案 1 :(得分:7)
numpy roll这样做。例如,如果原始数组是x,那么
for i in range(x.shape[1]):
x[:,i] = np.roll(x[:,i], i)
产生
[[11 36 19]
[17 12 37]
[35 18 13]]
答案 2 :(得分:5)
tom10's answer中的方法可以扩展到任意维度:
def shear3(a, strength=1, shift_axis=0, increase_axis=1):
if shift_axis > increase_axis:
shift_axis -= 1
res = numpy.empty_like(a)
index = numpy.index_exp[:] * increase_axis
roll = numpy.roll
for i in range(0, a.shape[increase_axis]):
index_i = index + (i,)
res[index_i] = roll(a[index_i], -i * strength, shift_axis)
return res
答案 3 :(得分:2)
以下是您自己方法的清理版本:
def shear2(a, strength=1, shift_axis=0, increase_axis=1, edges='clip'):
indices = numpy.indices(a.shape)
indices[shift_axis] -= strength * indices[increase_axis]
indices[shift_axis] %= a.shape[shift_axis]
res = a[tuple(indices)]
if edges == 'clip':
res[indices[shift_axis] < 0] = 0
res[indices[shift_axis] >= a.shape[shift_axis]] = 0
return res
主要区别在于它使用numpy.indices()
而不是滚动您自己的版本。
答案 4 :(得分:0)
r = lambda l, n: l[n:]+l[:n]
transpose(map(r, transpose(a), range(0, len(a)))
我想。您应该考虑这个伪代码而不是实际的Python。基本上转置数组,在其上映射一般旋转函数进行旋转,然后将其转置回来。