2016-11-01 99 views
6

垂直如何將一個(有效),請執行以下操作:NumPy的卷在二維數組

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]) 

但我怎麼返回全陣列與該換輥作爲一個新的副本?

回答

0

你必須覆蓋列

如:

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

卷帶負轉變:

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]]) 
0

這裏的推出一次過與advanced-indexing多列的方式 -

# 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]])