今天来整理一下numpy 数学库,主要用于数组计算
整理一下知识,使用更加得心应手。
有兴趣的码友一起学习一下吧。
点赞收藏关注。以资鼓励,谢谢~~~~
N 维数组对象 ndarray,它是一系列同类型数据的集合,以 0 下标为开始进行集合中元素的索引。
ndarray 中的每个元素在内存中都有相同存储大小的区域
ndarray 内部由以下内容组成:
numpy.array 构造器来创建
numpy.empty方法用来创建一个指定形状(shape)、数据类型(dtype)且未初始化的数组
numpy.zeros创建指定大小的数组,数组元素以 0 来填充
#order:创建数组的样式,C为行方向,F为列方向,A为任意方向
numpy.array(object, dtype = None, copy = True, order = None, subok = False,ndmin = 0)
#比如
a = np.array([1,2,3])
a = np.array([[1, 2], [3, 4]]) #两个维度2x2
a = np.array([1, 2, 3], dtype = complex) #复数
#order - "C"和"F"两个选项,分别代表,行优先和列优先,在计算机内存中的存储元素的顺序。
numpy.empty(shape, dtype = float, order = 'C')
#比如
x = np.empty([3,2], dtype = int)
numpy.ones创建指定形状的数组,数组元素以 1 来填充
numpy.arange创建数值范围并返回 ndarray 对象
通过冒号分隔切片参数 start:stop:step 来进行切片操作。
切片还可以包括省略号 …,来使选择元组的长度与数组的维度相同。 如果在行位置使用省略号,它
将返回包含行中元素的 ndarray。
numpy.reshape 函数可以在不改变数据的条件下修改形状
numpy.transpose 函数用于对换数组的维度,numpy.ndarray.T 类似 numpy.transpose
numpy.zeros(shape, dtype = float, order = 'C')
#比如
y = np.zeros((5,), dtype = np.int)
numpy.ones(shape, dtype = None, order = 'C')
#比如
x = np.ones([2,2], dtype = int)
#根据 start 与 stop 指定的范围以及 step 设定的步长,dtype数据类型生成ndarray
numpy.arange(start, stop, step, dtype)
#比如
x = np.arange(10,20,2)
x = np.arange(5)
a = np.array([[1,2,3],[3,4,5],[4,5,6]])
print(a)
print('从数组索引 a[1:] 处开始切割')
print(a[1:])
print (a[...,1]) # 第2列元素
print (a[1,...]) # 第2行元素
print (a[...,1:]) # 第2列及剩下的所有元素
numpy.reshape(arr, newshape, order='C')
#比如
a = np.arange(8)
print ('原始数组:')
print (a)
print ('\n')
b = a.reshape(4,2)
print ('修改后的数组:')
print (b)
numpy.transpose(arr, axes)
#比如
import numpy as np
a = np.arange(12).reshape(3,4)
print ('原数组:')
print (a )
print ('\n')
print ('对换数组:')
print (np.transpose(a))
numpy.expand_dims 函数通过在指定位置插入新的轴来扩展数组形状
numpy.expand_dims(arr, axis)
#比如
x = np.array(([1,2],[3,4]))
print ('数组 x:')
print (x)
print ('\n')
y = np.expand_dims(x, axis = 0)
print ('数组 y:')
print (y)
print ('\n')
print ('数组 x 和 y 的形状:')
print (x.shape, y.shape)
print ('\n')
numpy.squeeze 函数从给定数组的形状中删除一维的条目
numpy.squeeze(arr, axis)
#比如
x = np.arange(9).reshape(1,3,3)
print ('数组 x:')
print (x)
print ('\n')
y = np.squeeze(x)
print ('数组 y:')
print (y)
print ('\n')
print ('数组 x 和 y 的形状:')
print (x.shape, y.shape)
numpy.concatenate 函数用于沿指定轴连接相同形状的两个或多个数组
numpy.concatenate((a1, a2, …), axis)
#比如
a = np.array([[1,2],[3,4]])
b = np.array([[5,6],[7,8]])
print (np.concatenate((a,b),axis = 1))
如有帮助,点赞收藏关注!!!
如需转载,请注明出处!!!