一、更改形状
在对数组进行操作时,为了满足格式和计算的要求通常会改变其形状。
【例1-1】numpy.ndarray.shape
表示数组的维度,返回一个元组,这个元组的长度就是维度的数目,即 ndim 属性(秩)
import numpy as np
#通过shape属性改变数组的形状
x = np.array([1, 2, 9, 4, 5, 6, 7, 8])
print(x.shape) # (8,)
x.shape = [2, 4]
print(x)
# [[1 2 9 4]
# [5 6 7 8]]
【例1-2】numpy.ndarray.flat
将数组转换为一维的迭代器,可以用for访问数组每一个元素
import numpy as np
x = np.arange(12).reshape(3,4)
y = x.flat
for z in y:
print(z,end=' ')
【例1-3】numpy.ndarray.flatten([order=‘C’])
将数组的副本转换为一维数组,并返回。
a. order:‘C’ – 按行,‘F’ – 按列,‘A’ – 原顺序,‘k’ – 元素在内存中的出现顺序。(简记)
b. order:{'C / F,'A,K},可选使用此索引顺序读取a的元素。'C’意味着以行大的C风格顺序对元素进行索引,最后一个轴索引会更改F表示以列大的Fortran样式顺序索引元素,其中第一个索引变化最快,最后一个索引变化最快。请注意,'C’和’F’选项不考虑基础数组的内存布局,仅引用轴索引的顺序.
A’表示如果a为Fortran,则以类似Fortran的索引顺序读取元素在内存中连续,否则类似C的顺序。
“ K”表示按照步序在内存中的顺序读取元素,但步幅为负时反转数据除外。默认情况下,使用Cindex顺序。
import numpy as np
x = np.arange(12).reshape(3,4)
print(x)
y = x.flatten()
print(y)
y[3] = 0 #修改指定位置元素值
print(y)
print(x)
输出:
【例1-4】numpy.ravel(a, order=‘C’)
Return a contiguous flattened array.
ravel() 返回的是视图。
import numpy as np
x = np.arange(12).reshape(3,4) #构建3*4二维数组
y = x.ravel() #返回视图
print(y)
y[3] = 0
print(x)
输出
可以发现返回的视图是一维数组形式,修改视图的值,原数组的值也该变了。如果不想原数组值变动,设置参数order=‘F’即可
import numpy as np
x = np.arange(12).reshape(3,4) #构建3*4二维数组
y = x.ravel(order='F') #返回视图,order='F'就是拷贝
print(y)
print('--'*10)
y[3] = 0
print(y)
print('--'*10)
print(x)
输出:
【例1-5】numpy.reshape(a, newshape[, order=‘C’])
在不更改数据的情况下为数组赋予新的形状。
reshape() 函数当参数 newshape = [rows,-1] 时,将根据行数自动确定列数
reshape() 函数当参数 newshape = -1 时,表示将数组降为一维。
import numpy as np
x = np.arange(12)
y = np.reshape(x, [3, 4])
print(y.dtype) # int32
print(y)
# [[ 0 1 2 3]
# [ 4 5 6 7]
# [ 8 9 10 11]]
y = np.reshape(x, [3, -1]) #根据行数自动确定列数
print(y)
# [[ 0 1 2 3]
# [ 4 5 6 7]
# [ 8 9 10 11]]
y = np.reshape(x,[-1,3]) #根据列数自动确定行数
print(y)
# [[ 0 1 2]
# [ 3 4 5]
# [ 6 7 8]
# [ 9 10 11]]
y[0, 1] = 10 #第一行第二列的数改为10
print(x)
# [ 0 10 2 3 4 5 6 7 8 9 10 11](改变x去reshape后y中的值,x对应元素也改变)
reshape() 函数当参数 newshape = -1 时,表示将数组降至一维。
import numpy as np
x = np.random.randint(12, size=[2, 2, 3])
print(x)
# [[[11 9 1]
# [ 1 10 3]]
#
# [[ 0 6 1]
# [ 4 11 3]]]
y = np.reshape(x, -1)
print(y)
# [11 9 1 1 10 3 0 6 1 4 11 3]
二、数组转置
【例2-1】转置
- numpy.transpose(a, axes=None) Permute the dimensions of an array.
- numpy.ndarray.T Same as self.transpose() , except that self is returned if self.ndim < 2
代码如下:
import numpy as np
x = np.arange(25).reshape(5,5)
print(x)
#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]])
y = x