所有的numpy用np表示,即import numpy as np。
主要介绍numpy中的四个常量np.nan,np.inf,np.pi,np.e。
表示空值,但是两个np.nan是不相等的。
print(np.nan == np.nan) # False与np.nan相对,表示无穷大,不同的是两个np.inf是相等的。
print(np.inf == np.inf) # True表示圆周率,在我的电脑上(win10系统)输出了15位小数,没尝试其他电脑。
print(np.pi) # print(np.pi)表示自然常数,同圆周率,在我的电脑上(win10系统)输出了15位小数。
print(np.e) # 2.718281828459045Python原生的数据类型有, bool、int、float、str等,为了加以区分 numpy 在这些类型名称末尾都加了“_”。 numpy 的数值类型实际上是 dtype 对象的实例
class dtype(object): def __init__(self, obj, align=False, copy=False): pass每个内建类型都有一个唯一定义它的字符代码,如下:
字符对应类型备注bboolean‘b1’isigned integer‘i1’, ‘i2’, ‘i4’, ‘i8’uunsigned integer‘u1’, ‘u2’ ,‘u4’ ,‘u8’ffloating-point‘f2’, ‘f4’, ‘f8’ccomplex floating-pointmtimedelta64表示两个时间之间的间隔Mdatetime64日期时间类型OobjectS(byte-)stringS3表示长度为3的字符串UUnicodeUnicode 字符串Vvoid在 numpy 中,我们很方便的将字符串转换成时间日期类型 datetime64。
从字符串创建 datetime64 类型时,默认情况下,numpy 会根据字符串自动选择对应的单位。
import numpy as np a = np.datetime64('2020-03-01') print(a, a.dtype) # 2020-03-01 datetime64[D] a = np.datetime64('2020-03') print(a, a.dtype) # 2020-03 datetime64[M] a = np.datetime64('2020-03-08 20:00:05') print(a, a.dtype) # 2020-03-08T20:00:05 datetime64[s] a = np.datetime64('2020-03-08 20:00') print(a, a.dtype) # 2020-03-08T20:00 datetime64[m] a = np.datetime64('2020-03-08 20') print(a, a.dtype) # 2020-03-08T20 datetime64[h]numpy 提供的最重要的数据结构是ndarray,它是 python 中list的扩展。
array()和asarray()都可以将结构数据转化为 ndarray,但是array()和asarray()主要区别就是当数据源是ndarray 时,array()仍然会 copy 出一个副本,占用新的内存,但不改变 dtype 时 asarray()不会。
def asarray(a, dtype=None, order=None): return array(a, dtype, copy=False, order=order)array()和asarray()都可以将结构数据转化为 ndarray
import numpy as np x = [[1, 1, 1], [1, 1, 1], [1, 1, 1]] y = np.array(x) z = np.asarray(x) x[1][2] = 2 print(x,type(x)) # [[1, 1, 1], [1, 1, 2], [1, 1, 1]] <class 'list'> print(y,type(y)) # [[1 1 1] # [1 1 1] # [1 1 1]] <class 'numpy.ndarray'> print(z,type(z)) # [[1 1 1] # [1 1 1] # [1 1 1]] <class 'numpy.ndarray'>array()和asarray()的区别。(array()和asarray()主要区别就是当数据源是ndarray 时,array()仍然会 copy 出一个副本,占用新的内存,但不改变 dtype 时 asarray()不会。)
import numpy as np x = np.array([[1, 1, 1], [1, 1, 1], [1, 1, 1]]) y = np.array(x) z = np.asarray(x) w = np.asarray(x, dtype=np.int) x[1][2] = 2 print(x,type(x),x.dtype) # [[1 1 1] # [1 1 2] # [1 1 1]] <class 'numpy.ndarray'> int32 print(y,type(y),y.dtype) # [[1 1 1] # [1 1 1] # [1 1 1]] <class 'numpy.ndarray'> int32 print(z,type(z),z.dtype) # [[1 1 1] # [1 1 2] # [1 1 1]] <class 'numpy.ndarray'> int32 print(w,type(w),w.dtype) # [[1 1 1] # [1 1 2] # [1 1 1]] <class 'numpy.ndarray'> int32更改为较大的dtype时,其大小必须是array的最后一个axis的总大小(以字节为单位)的除数
import numpy as np x = np.array([[1, 1, 1], [1, 1, 1], [1, 1, 1]]) print(x, x.dtype) # [[1 1 1] # [1 1 1] # [1 1 1]] int32 x.dtype = np.float # ValueError: When changing to a larger dtype, its size must be a divisor of the total size in bytes of the last axis of the array.给函数绘图的时候可能会用到fromfunction(),该函数可从函数中创建数组。
def fromfunction(function, shape, **kwargs):通过在每个坐标上执行一个函数来构造数组。
import numpy as np def f(x, y): return 10 * x + y x = np.fromfunction(f, (5, 4), dtype=int) print(x) # [[ 0 1 2 3] # [10 11 12 13] # [20 21 22 23] # [30 31 32 33] # [40 41 42 43]] x = np.fromfunction(lambda i, j: i == j, (3, 3), dtype=int) print(x) # [[ True False False] # [False True False] # [False False True]] x = np.fromfunction(lambda i, j: i + j, (3, 3), dtype=int) print(x) # [[0 1 2] # [1 2 3] # [2 3 4]]在机器学习任务中经常做的一件事就是初始化参数,需要用常数值或者随机值来创建一个固定大小的矩阵。
结构数组,首先需要定义结构,然后利用np.array()来创建数组,其参数dtype为定义的结构。
在使用 numpy 时,你会想知道数组的某些信息。很幸运,在这个包里边包含了很多便捷的方法,可以给你想要的信息。
numpy.ndarray.ndim用于返回数组的维数(轴的个数)也称为秩,一维数组的秩为 1,二维数组的秩为 2,以此类推。numpy.ndarray.shape表示数组的维度,返回一个元组,这个元组的长度就是维度的数目,即 ndim 属性(秩)。numpy.ndarray.size数组中所有元素的总量,相当于数组的shape中所有元素的乘积,例如矩阵的元素总量为行与列的乘积。numpy.ndarray.dtype ndarray 对象的元素类型。numpy.ndarray.itemsize以字节的形式返回数组中每一个元素的大小。 class ndarray(object): shape = property(lambda self: object(), lambda self, v: None, lambda self: None) dtype = property(lambda self: object(), lambda self, v: None, lambda self: None) size = property(lambda self: object(), lambda self, v: None, lambda self: None) ndim = property(lambda self: object(), lambda self, v: None, lambda self: None) itemsize = property(lambda self: object(), lambda self, v: None, lambda self: None) import numpy as np a = np.array([1, 2, 3, 4, 5]) print(a.shape) # (5,) print(a.dtype) # int32 print(a.size) # 5 print(a.ndim) # 1 print(a.itemsize) # 4 b = np.array([[1, 2, 3], [4, 5, 6.0]]) print(b.shape) # (2, 3) print(b.dtype) # float64 print(b.size) # 6 print(b.ndim) # 2 print(b.itemsize) # 8在ndarray中所有元素必须是同一类型,否则会自动向下转换,int->float->str。
import numpy as np a = np.array([1, 2, 3, 4, 5]) print(a) # [1 2 3 4 5] b = np.array([1, 2, 3, 4, '5']) print(b) # ['1' '2' '3' '4' '5'] c = np.array([1, 2, 3, 4, 5.0]) print(c) # [1. 2. 3. 4. 5.]