# numpy array索引和切片

## 一维数组

import numpy as np

arr = np.arange( 10)
arr


array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])


arr[4] # 索引（注意是从0开始的）


4


arr[3:6]


array([3, 4, 5])


arr_old = arr.copy()
arr_old


array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])


arr[3:6] = 33
arr


array([ 0,  1,  2, 33, 33, 33,  6,  7,  8,  9])


arr_old


array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])


## 二维数组

arr1 = np.array([[1, 2, 3],[4, 5, 6],[7, 8, 9]])

arr1[0]
Out[13]: array([1, 2, 3])

arr1[1,2]
Out[14]: 6


## 多维数组

np.reshape(a, newshape, order='C')


np.reshape()不更改原数组形状（会生成一个副本）

arr1 = np.arange(12)
arr2 = arr1.reshape(2,2,3) #将arr1变为2×2×3数组

arr2
Out[9]:
array([[[ 0,  1,  2],
[ 3,  4,  5]],
[[ 6,  7,  8],
[ 9, 10, 11]]])

arr2[0]
Out[10]:
array([[0, 1, 2],
[3, 4, 5]])

arr2[1]
Out[11]:
array([[ 6,  7,  8],
[ 9, 10, 11]])

arr2[0,1]
Out[12]: array([3, 4, 5])

arr2[0] = 23 #赋值
arr2
Out[15]:
array([[[23, 23, 23],
[23, 23, 23]],
[[ 6,  7,  8],
[ 9, 10, 11]]])


## 切片索引

arr1 = np.arange(36)#创建一个一维数组。

arr2 = arr1.reshape(6,6) #更改数组形状。
Out[20]:
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]])


arr2[0,2:4]
Out[29]: array([2, 3])


arr2[1] #取得第2行
Out[37]: array([ 6,  7,  8,  9, 10, 11])

arr2[:,3] #取得第3列, 只有：代表选取整列（也就是整个轴）
Out[38]: array([ 3,  9, 15, 21, 27, 33])

arr2[1:4,2:4] # 取得一个二维数组
Out[40]:
array([[ 8,  9],
[14, 15],
[20, 21]])

arr2[::2,::2] #设置步长为2
Out[41]:
array([[ 0,  2,  4],
[12, 14, 16],
[24, 26, 28]])

arr3 = arr2.reshape(4,3,3)

arr3[2:,:1] = 22 #对切片表达式赋值

arr3
Out[25]:
array([[[ 0,  1,  2],
[ 3,  4,  5],
[ 6,  7,  8]],

[[ 9, 10, 11],
[12, 13, 14],
[15, 16, 17]],

[[22, 22, 22],
[21, 22, 23],
[24, 25, 26]],

[[22, 22, 22],
[30, 31, 32],
[33, 34, 35]]])