![](/img/trans.png)
[英]How do you rotate the numbers in an numpy array of shape (n,) or (n,1)?
[英]How do you rotate elements in a 2D numpy array by 'n' units?
x = [[1, 2, 3],
[4, 5, 6],
[7, 8, 9]]
輪換1個單位應該給:
x = [[4, 1, 2],
[7, 5, 3],
[8, 9, 6]]
基本上,我想用'n'單位移動數組中的每個圓形層。
我看了numpy.roll,但無法想出將它用於此用例。 我不能使用像scipy.ndimage.interpolation.rotate這樣的圖像旋轉例程,因為它們會改變形狀而不能完全達到預期的效果。
編輯:
對於4 X 4矩陣:
x = [[a, b, c, d],
[e, f, g, h],
[i, j, k, l],
[m, n, o, p]]
輪換1個單位應該給:
x = [[e, a, b, c],
[i, j, f, d],
[m, k, g, h],
[n, o, p, l]]
編輯:
添加一些關於如何適用於任意大小的說明。
對於旋轉1個單位的NXN矩陣,外部“環”首先移位1.相同的邏輯遞歸地跟隨剩余的“內部”(N-2)X(N-2)矩陣。
這是一種方法,假設您正在尋找旋轉,使得切片的量在切片上是恆定的,其中切片是指從中心向外指向的最外層元素 -
def outer_slice(x):
return np.r_[x[0],x[1:-1,-1],x[-1,:0:-1],x[-1:0:-1,0]]
def rotate_steps(x, shift):
out = np.empty_like(x)
N = x.shape[0]
idx = np.arange(x.size).reshape(x.shape)
for n in range((N+1)//2):
sliced_idx = outer_slice(idx[n:N-n,n:N-n])
out.ravel()[sliced_idx] = np.roll(np.take(x,sliced_idx), shift)
return out
樣品運行
案例#1(3 x 3陣列):
In [444]: x
Out[444]:
array([[24, 85, 97],
[51, 33, 11],
[86, 38, 33]])
In [445]: rotate_steps(x,shift=1)
Out[445]:
array([[51, 24, 85],
[86, 33, 97],
[38, 33, 11]])
案例#2(4 x 4陣列):
In [447]: x
Out[447]:
array([[11, 70, 28, 13],
[44, 41, 17, 82],
[47, 32, 89, 25],
[32, 20, 67, 98]])
In [448]: rotate_steps(x,shift=1)
Out[448]:
array([[44, 11, 70, 28],
[47, 32, 41, 13],
[32, 89, 17, 82],
[20, 67, 98, 25]])
In [449]: rotate_steps(x,shift=2)
Out[449]:
array([[47, 44, 11, 70],
[32, 89, 32, 28],
[20, 17, 41, 13],
[67, 98, 25, 82]])
對於3x3陣列,您可以使用np.roll
和ndarray.flat
完成此ndarray.flat
:
>>> x = np.arange(1, 10).reshape((3, 3))
>>> x
array([[1, 2, 3],
[4, 5, 6],
[7, 8, 9]])
>>> i = np.array([0, 1, 2, 5, 8, 7, 6, 3]) # Indices in circular order
>>> x.flat[i]
array([1, 2, 3, 6, 9, 8, 7, 4])
旋轉1個單位:
>>> x.flat[i] = np.roll(x.flat[i], 1) # Rotate indices and reassign
>>> x
array([[4, 1, 2],
[7, 5, 3],
[8, 9, 6]])
旋轉4個單位:
>>> x.flat[i] = np.roll(x.flat[i], 4)
>>> x
array([[9, 8, 7],
[6, 5, 4],
[3, 2, 1]])
對於4x4的情況,我仍然需要清楚每個“圓圈”是否需要根據它們的長度以不同的“速度”旋轉......
你在矩陣上應用了一個排列。 排列通常由向量(i - > p [i])表示,並應用於向量。 如果需要,可以表示矩陣在矩陣中的排列,排列將是對的矩陣,以便(i,j)處的元素移動到m [i,j]。
構建矩陣后,只需要一個簡單的循環來應用置換。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.