我正在创建一个2d numpy数组,其简化示例如下:
COL01 = np.array(["A", "D", "G"])
COL02 = np.array(["B", "E", "H"])
COL03 = np.array(["C", "F", "I"])
GRID = np.array([[COL01], [COL02], [COL03]])
我在我的代码中传递了GRID。我希望能够通过只滚动构成其组件行的一个数组来修改GRID。例如,我想将GRID传递给一个具有行号和要滚动的位置数的函数,然后返回结果。
如何独立滚动单行?我试着从这里得到答案: [Roll rows of a matrix independently,但我无法弄清楚如何根据我的问题调整答案。
答案 0 :(得分:4)
您可以通过选择要操作的行并使用numpy.roll
来完成此操作。
假设我们想要将第一行向右滚动一个位置:
import numpy as np
grid = np.array([['A', 'D', 'G'],
['B', 'E', 'H'],
['C', 'F', 'I']])
grid[0] = np.roll(grid[0], 1)
print grid
这会产生:
[['G' 'A' 'D']
['B' 'E' 'H']
['C' 'F' 'I']]
请注意,我们正在修改原始数组。
您应该决定是否要在原地对阵列进行操作(修改原始阵列),或者每次是否要复制。根据您的决定,重复调用会产生不同的效果:
import numpy as np
def independent_roll_inplace(arr, ind, amount):
arr[ind] = np.roll(arr[ind], amount)
def independent_roll_copy(arr, ind, amount):
arr = arr.copy()
arr[ind] = np.roll(arr[ind], amount)
return arr
grid = np.array([['A', 'D', 'G'],
['B', 'E', 'H'],
['C', 'F', 'I']])
作为差异的一个例子,如果我们每次都复制一份,我们就会用原始网格开始“新鲜”。重复呼叫对原始呼叫没有影响:
print 'Roll the second row one place'
print independent_roll_copy(grid, 1, 1)
print 'Roll the second row two places'
print independent_roll_copy(grid, 1, 2)
print 'Roll the second row three places'
print independent_roll_copy(grid, 1, 3)
这会产生:
Roll the second row one place
[['A' 'D' 'G']
['H' 'B' 'E']
['C' 'F' 'I']]
Roll the second row two places
[['A' 'D' 'G']
['E' 'H' 'B']
['C' 'F' 'I']]
Roll the second row three places
[['A' 'D' 'G']
['B' 'E' 'H']
['C' 'F' 'I']]
但是,如果我们每次都修改原文,我们会多次滚动一个地方得到相同的结果:
for _ in range(3):
print 'Roll the first row one place, modifying the original'
independent_roll_inplace(grid, 0, 1)
print grid
产量:
Roll the second row one place, modifying the original
[['A' 'D' 'G']
['H' 'B' 'E']
['C' 'F' 'I']]
Roll the second row one place, modifying the original
[['A' 'D' 'G']
['E' 'H' 'B']
['C' 'F' 'I']]
Roll the second row one place, modifying the original
[['A' 'D' 'G']
['B' 'E' 'H']
['C' 'F' 'I']]
答案 1 :(得分:0)
此代码可能会解决您的问题。
REV_GRID是GRID的翻转版本。
COL01 = ["A", "D", "G"]
COL02 = ["B", "E", "H"]
COL03 = ["C", "F", "I"]
GRID = []
GRID.append(COL01)
GRID.append(COL02)
GRID.append(COL03)
REV_GRID = []
for col in GRID:
REV_GRID.append(col[::-1])
print GRID
print REV_GRID
如果它无法解决您的问题,请告诉我。我们将继续努力。