1、二维数组
import numpy as np
a = np.array([[1,2,3],[4,5,6],[7,8,9]])
#[[1 2 3]
[4 5 6]
[7 8 9]]
#每个轴一个索引,当提供的索引数少于轴数时,缺少的索引将被视为完整切片,第一个数表示行,第二个数表示列,中间用逗号隔开
a[0,1] #2
a[0:3,1] #array([2, 5, 8])
a[-1] #array([7, 8, 9])
a[:,-1] #array([3, 6, 9])
2、三维数据
c = np.array([[(2,3,4),(5,6,7)],[(1,3,7),(9,5,3)]])
##[[[2 3 4]
[5 6 7]]
[[1 3 7]
[9 5 3]]]
c.shape #(2, 2, 3)
##...表示生成完整索引元组所需的任意数量的冒号
c[1,...]
#array([[1, 3, 7],
[9, 5, 3]])
c[...,1]
#array([[3, 6],
[3, 5]])
c[1,1,2] #3
c[:,0,:]
#array([[2, 3, 4],
[1, 3, 7]])
3、打印数组中每个元素
c = [[2 3 4]
[5 6 7]]
[[1 3 7]
[9 5 3]]
for row in c:
print(row)
#[[2 3 4]
[5 6 7]]
[[1 3 7]
[9 5 3]]
for row in c.flat:
print(row)
#2
3
4
5
6
7
1
3
7
9
5
3
4、更改数据形状
c = [[2 3 4]
[5 6 7]]
[[1 3 7]
[9 5 3]]
##这三种方法都返回已修改的数组,但不更改原始数组
##展开
c.ravel()
#array([2, 3, 4, 5, 6, 7, 1, 3, 7, 9, 5, 3])
c.reshape(6,2)
#array([[2, 3],
[4, 5],
[6, 7],
[1, 3],
[7, 9],
[5, 3]])
c.T
#array([[[2, 1],
[5, 9]],
[[3, 3],
[6, 5]],
[[4, 7],
[7, 3]]])
c.T.shape #(3, 2, 2)
#resize方法修改数组本身
c.resize(2,6)
print(c)
#[[2 3 4 5 6 7]
[1 3 7 9 5 3]]
5、数据拼接
##纵向拼接使用np.vstack((a,b))或者np.row_stack((a,b))
横向拼接使用np.hstack((a,b))或者np.column_stack((a,b))
c = np.array([[(2,3,4),(5,6,7)],[(1,3,7),(9,5,3)]]) #(2,2,3)
d = np.array([[(12,14,15),(11,17,18)],[(0,0,0),(0,0,0)]]) #(2,2,3)
np.concatenate((c,d),axis=0) #(4,2,3)
#array([[[ 2, 3, 4],
[ 5, 6, 7]],
[[ 1, 3, 7],
[ 9, 5, 3]],
[[12, 14, 15],
[11, 17, 18]],
[[ 0, 0, 0],
[ 0, 0, 0]]])
np.concatenate((c,d),axis=1) (2,4,3)
#array([[[ 2, 3, 4],
[ 5, 6, 7],
[12, 14, 15],
[11, 17, 18]],
[[ 1, 3, 7],
[ 9, 5, 3],
[ 0, 0, 0],
[ 0, 0, 0]]])
|