1、多维数组
多维数组的存取和一维数组类似,因为多维数组有多个轴,因此它的下标需要用多个值来表示,NumPy采用元组 (tuple)作为数组的下标。
#创建多维数组
import numpy as np
a = np.arange(0,60,10).reshape(-1,1) + np.arange(0,6)
#存取数组
a[0,3:5] #返回:array([3, 4])
a[2::2,::2] #返回:array([[20, 22, 24],
[40, 42, 44]])
多维数组同样也可以使用整数序列和布尔数组进行存取。
a[(0,1,2,3,4),(1,2,3,4,5)] #返回:array([ 1, 12, 23, 34, 45])
a[3:,[0,2,5]]
#返回:array([[30, 32, 35],
[40, 42, 45],
[50, 52, 55]])
mask = np.array([1,0,1,0,0,1],dtype = np.bool)
a[mask,2] #返回: array([ 2, 22, 52])
2、numpy数组的操作
反转操作
np.reshape( )
参数:
- a:数组——需要处理的数据
- newshape:新的格式——整数或整数数组
- order:默认参数为’C’,可选范围为{‘C’,‘F’,‘A’}
b = np.array([[1,2,3,4],[5,6,7,8],[9,10,11,12]])
print(b)
#[[ 1 2 3 4]
[ 5 6 7 8]
[ 9 10 11 12]]
c = b.reshape(2,6)
print(c)
#[[ 1 2 3 4 5 6]
[ 7 8 9 10 11 12]]
c1 = b.reshape(2,6,order = 'F')
print(c1)
#[[ 1 9 6 3 11 8]
[ 5 2 10 7 4 12]]
np.ndarray.flat 与 np .ndarray.flatten( )
区别:
flat返回的是一个迭代器,可以使用for访问数组的每一个元素;flatten将数组的副本转换为一个维度,并返回
d = b.flat
print(d) #<numpy.flatiter object at 0x0000028E1260F920>
print(list(c)) #[ 1 2 3 4 5 6 7 8 9 10 11 12]
print(b.flatten()) #[ 1 2 3 4 5 6 7 8 9 10 11 12]
id(b) #2809290986400
#生成b的一个副本
e = b.flatten()
print(id(e)) #2809290989280
np.ndarray.T——矩阵转置
print(b)
#[[ 1 2 3 4]
[ 5 6 7 8]
[ 9 10 11 12]]
print(b.T)
#[[ 1 5 9]
[ 2 6 10]
[ 3 7 11]
[ 4 8 12]]
连接操作
np.concatenate( )
●传入的参数必须是一个多个数组的元组或者列表
●另外需要指定拼接的方向,默认是axis = 0 ,也就是说对0轴的数组对象进行纵向的拼接(纵向的拼接沿着axis= 1方向) ;注:一般axis = 0,就是对该轴向的数组进行操作,操作方向是另外-个轴,即axis=1。
●传入的数组必须具有相同的形状,这里的相同的形状可以满足在拼接方向axis轴.上数组间的形状一致即可
a = np.arange(6).reshape(2,3)
print(a)
#[[0 1 2]
[3 4 5]]
b = np.array([[7,8,9],[10,11,12]])
print(b)
#[[ 7 8 9]
[10 11 12]]
print(np.concatenate((a,b))) #默认沿着0轴进行链接
#[[ 0 1 2]
[ 3 4 5]
[ 7 8 9]
[10 11 12]]
print(np.concatenate((a,b),axis=1))
#[[ 0 1 2 7 8 9]
[ 3 4 5 10 11 12]]
np.stack( )沿着新轴连接数组的序列
axis参数指定新轴在结果尺寸中的索引。例如,如果axis=0 ,它将是第一个维度,如果axis=-1 ,它将是最后一个维度。
●参数:数组: array like的序列每个数组必须具有相同的形状。axis : int ,可选输入数组沿其堆叠的结果数组中的轴。
●返回:堆叠: ndarray堆叠数组比输入数组多一个维。
a = np.arange(1,7).reshape((2,3))
b = np.arange(7,13).reshape((2,3))
c = np.arange(13,19).reshape((2,3))
s = np.stack((a,b,c),axis = 0)
print('axis = 0 \n',s.shape,'\n',s)
#
axis = 0
(3, 2, 3)
[[[ 1 2 3]
[ 4 5 6]]
[[ 7 8 9]
[10 11 12]]
[[13 14 15]
[16 17 18]]]