索引:1.整数索引
获取数组的单个元素,多维数组的子数组。
x=np.array([1,2,3,4,5,6])
print(x[3])
4
x=np.array([[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]])
print(x)
print(x[2],x[2][1],x[2,1])
[[ 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]]
[13 14 15 16 17 18] 14 14
2.切片索引
切片即从数组中抽取一部分元素组成新的数组。
对Python 列表 进行切片操作,得到的数组是原数组的 副本,即修改切片后,原数组不变。
对Numpy数据进行切片操作,得到的数组是指向相同缓冲区的 视图。
一维数组:
a=np.array([1,2,3,4,5,6,7,8,9,10])
b=a[0:9:2]
c=a[0:9]
d=a[4:]
e=a[:4]
f=a[:]
g=a[:-2]
h=a[-2:]
print(b)
print(c)
print(d)
print(e)
print(f)
print(g)
print(h)
[1 3 5 7 9]
[1 2 3 4 5 6 7 8 9]
[ 5 6 7 8 9 10]
[1 2 3 4]
[ 1 2 3 4 5 6 7 8 9 10]
[1 2 3 4 5 6 7 8]
[ 9 10]
负数下标翻转:
i=a[::-1]
print(i)
[10 9 8 7 6 5 4 3 2 1]
二维数组,切片的第一片定义了行的切片,第二片定义了列的切片:
x=np.array([[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]])
a=x[2,3]
b=x[2][3]
c=x[1:4:4]
d=x[1:]
e=x[:2]
f=x[-2:]
g=x[:]
h=x[1,:]
i=x[:,2]
k=x[1:2,3:4]
print(a,"\n**")
print(b,"\n**")
print(c,"\n**")
print(d,"\n**")
print(e,"\n**")
print(f,"\n**")
print(g,"\n**")
print(h,"\n**")
print(i,"\n**")
print(k,"\n**")
16
**
16
**
[[ 7 8 9 10 11 12]]
**
[[ 7 8 9 10 11 12]
[13 14 15 16 17 18]
[19 20 21 22 23 24]
[25 26 27 28 29 30]]
**
[[ 1 2 3 4 5 6]
[ 7 8 9 10 11 12]]
**
[[19 20 21 22 23 24]
[25 26 27 28 29 30]]
**
[[ 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]]
**
[ 7 8 9 10 11 12]
**
[ 3 9 15 21 27]
**
[[10]]
**