# python 切片NumPy 2d數組，或者如何從nxn數組（n> m）中提取mxm子矩陣？

NumPy通過引入大步解決了這個問題。 當計算訪問`x[i,j]`的內存偏移量時，實際計算的是`i*x.strides[0]+j*x.strides[1]` （並且這已經包含了int大小的因子） ：

``````x.strides
(16, 4)
``````

``````y.shape
(2,2)
y.strides
(16, 4)
``````

``````x[[[1],[3]],[1,3]]
``````

``````x[1::2, 1::2]
``````
python numpy slice

``````from numpy import *
x = range(16)
x = reshape(x,(4,4))

print x
[[ 0  1  2  3]
[ 4  5  6  7]
[ 8  9 10 11]
[12 13 14 15]]
``````

``````In [33]: x[0:2,0:2]
Out[33]:
array([[0, 1],
[4, 5]])

In [34]: x[2:,2:]
Out[34]:
array([[10, 11],
[14, 15]])
``````

``````In [35]: x[[1,3],[1,3]]
Out[35]: array([ 5, 15])
``````

``````    In [61]: x[[1,3]][:,[1,3]]
Out[61]:
array([[ 5,  7],
[13, 15]])
``````

``````In [49]: x=np.arange(16).reshape((4,4))
In [50]: x[1:4:2,1:4:2]
Out[50]:
array([[ 5,  7],
[13, 15]])
``````

``````In [51]: y=x[1:4:2,1:4:2]

In [52]: y[0,0]=100

In [53]: x   # <---- Notice x[1,1] has changed
Out[53]:
array([[  0,   1,   2,   3],
[  4, 100,   6,   7],
[  8,   9,  10,  11],
[ 12,  13,  14,  15]])
``````

`z=x[(1,3),:][:,(1,3)]`使用高級索引並返回一個副本：

``````In [58]: x=np.arange(16).reshape((4,4))
In [59]: z=x[(1,3),:][:,(1,3)]

In [60]: z
Out[60]:
array([[ 5,  7],
[13, 15]])

In [61]: z[0,0]=0
``````

``````In [62]: x
Out[62]:
array([[ 0,  1,  2,  3],
[ 4,  5,  6,  7],
[ 8,  9, 10, 11],
[12, 13, 14, 15]])
``````

``````columns_to_keep = [1,3]
rows_to_keep = [1,3]
``````

``````x[np.ix_(rows_to_keep, columns_to_keep)]
``````

``````array([[ 5,  7],
[13, 15]])
``````

### Tags

python   numpy   slice