在二维数组中垂直滚动Numpy

7

如何(高效地)完成以下任务:

x = np.arange(49)
x2 = np.reshape(x, (7,7))

x2
array([[ 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, 27],
       [28, 29, 30, 31, 32, 33, 34],
       [35, 36, 37, 38, 39, 40, 41],
       [42, 43, 44, 45, 46, 47, 48]])

我想要滚动几个东西。 我想要滚动0、7、14、21等,使14到达顶部。 然后再滚动4、11、18、25等,使39到达顶部。
结果应该是:

x2
array([[14,  1,  2,  3, 39,  5,  6],
       [21,  8,  9, 10, 46, 12, 13],
       [28, 15, 16, 17,  4, 19, 20],
       [35, 22, 23, 24, 11, 26, 27],
       [42, 29, 30, 31, 18, 33, 34],
       [ 0, 36, 37, 38, 25, 40, 41],
       [ 7, 43, 44, 45, 32, 47, 48]])

我查了一下numpy.roll的文档和谷歌,但是没有找到如何进行这个操作的方法。
对于水平滚动,我可以这样做:

np.roll(x2[0], 3, axis=0)

x3
array([4, 5, 6, 0, 1, 2, 3])

但是如何将这个滚动更改后的完整数组作为新副本返回?
4个回答

5

带有负偏移量的滚动:

x2[:, 0] = np.roll(x2[:, 0], -2)

积极应对变化:

x2[:, 4] = np.roll(x2[:, 4], 2)

提供:
>>>x2
array([[14,  1,  2,  3, 39,  5,  6],
       [21,  8,  9, 10, 46, 12, 13],
       [28, 15, 16, 17,  4, 19, 20],
       [35, 22, 23, 24, 11, 26, 27],
       [42, 29, 30, 31, 18, 33, 34],
       [ 0, 36, 37, 38, 25, 40, 41],
       [ 7, 43, 44, 45, 32, 47, 48]])

4

这里有一种使用高级索引一次性滚动多列的方法 -

# Params
cols = [0,4]  # Columns to be rolled
dirn = [2,-2] # Offset with direction as sign

n = x2.shape[0]
x2[:,cols] = x2[np.mod(np.arange(n)[:,None] + dirn,n),cols]

示例运行 -


In [45]: x2
Out[45]: 
array([[ 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, 27],
       [28, 29, 30, 31, 32, 33, 34],
       [35, 36, 37, 38, 39, 40, 41],
       [42, 43, 44, 45, 46, 47, 48]])

In [46]: cols = [0,4,5]  # Columns to be rolled
    ...: dirn = [2,-2,4] # Offset with direction as sign
    ...: n = x2.shape[0]
    ...: x2[:,cols] = x2[np.mod(np.arange(n)[:,None] + dirn,n),cols]
    ...: 

In [47]: x2  # Three columns rolled
Out[47]: 
array([[14,  1,  2,  3, 39, 33,  6],
       [21,  8,  9, 10, 46, 40, 13],
       [28, 15, 16, 17,  4, 47, 20],
       [35, 22, 23, 24, 11,  5, 27],
       [42, 29, 30, 31, 18, 12, 34],
       [ 0, 36, 37, 38, 25, 19, 41],
       [ 7, 43, 44, 45, 32, 26, 48]])

0

你必须覆盖该列

e.g.:

x2[:,0] = np.roll(x2[:,0], 3)

0

这里有一个有用的方法,可以将2D数组向所有4个方向(上、下、左、右)移动:

def image_shift_roll(img, x_shift, y_roll):
    img_roll = img.copy()
    img_roll = np.roll(img_roll, -y_roll, axis = 0)    # Positive y rolls up
    img_roll = np.roll(img_roll, x_roll, axis = 1)     # Positive x rolls right
    return img_roll

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接