NumPy 中定义的最重要的对象是称为 ndarray 的 N 维数组类型,它是描述相同类型的元素集合。ndarray 中的每个元素都是数据类型对象(dtype)的对象。ndarray 中的每个元素在内存中使用相同大小的块
ndarray的含义是The N-dimensional array,意思就是N维数组
注:默认import numpy as np已经写在每段代码前,不再重复写入
【例1-1】通过array()函数进行创建
>>>datas = [x for x in range(5)] # 创建一维数组 >>>a = np.array(datas) >>>b = np.array(tuple(datas)) >>>print(a, type(a)) >>>print(b, type(b)) >>>print(a.shape,b.shape) [0 1 2 3 4] <class 'numpy.ndarray'> [0 1 2 3 4] <class 'numpy.ndarray'> (5,) (5,) # 创建二维数组 >>>c = np.array([a]*2) >>>print(c, type(c)) [[0 1 2 3 4] [0 1 2 3 4]] <class 'numpy.ndarray'> (2, 5)我们可以看到使用array时,传入的数据类型可以是list,也可以是tuple。有一个小技巧n维数组的array()内的左括号数等于n,例如:
array()和asarray()都可以将结构数据转化为 ndarray,但是array()和asarray()主要区别就是当数据源是ndarray 时,array()仍然会 copy 出一个副本,占用新的内存,但不改变 dtype 时 asarray()不会。
如果改变dtype,例如int转成float,那么不用占用新的内存,即保持一致。
def asarray(a, dtype=None, order=None): return array(a, dtype, copy=False, order=order) #`array()`和`asarray()`都可以将结构数据转化为 ndarray >>>x = [[1, 1, 1], [1, 1, 1], [1, 1, 1]] >>>y = np.array(x) >>>z = np.asarray(x) >>>#改变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'> #当数据源是ndarray时 >>>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可见w随着x的变化而变化,而不是在一个新的内存中
#更改为较大的dtype时,其大小必须是array的最后一个axis的总大小(以字节为单位)的除数 >>>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.怎么理解上面的错误,很简单,画个图示意一下:
假设我们之前有4个int8,总共32个单位,那么新的dtype可以是int16,可以是int32,但是不能是int64,因为int64装完32之后还有空余。
给函数绘图的时候可能会用到fromfunction(),该函数可从函数中创建数组。
def fromfunction(function, shape, **kwargs): #通过在每个坐标上执行一个函数来构造数组 >>>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]]上述的f也可以直接替换为lambda函数, 即np.fromfunction(lambda i, j: 10*i+j, (5, 5), dtype=int)
在机器学习任务中经常做的一件事就是初始化参数,需要用常数值或者随机值来创建一个固定大小的矩阵。
【例】
>>>x = np.zeros(5) >>>print(x) # [0. 0. 0. 0. 0.] >>>x = np.zeros([2, 3]) >>>print(x) [[0. 0. 0.] [0. 0. 0.]] >>>x = np.array([[1, 2, 3], [4, 5, 6]]) >>>y = np.zeros_like(x) >>>print(y) [[0 0 0] [0 0 0]]1数组的用法和零数组相同,不加赘述
【例】
>>>x = np.empty(5) >>>print(x) [0. 0. 0. 0. 0.] >>>x = np.empty((3, 2)) >>>print(x) [[0. 0.] [0. 0.] [0. 0.]]注:当参数是ndarray时,表示提取对角线;参数是list时,表示构建对角数组
结构数组,首先需要定义结构,然后利用np.array()来创建数组,其参数dtype为定义的结构。
只需将
{ 'names': ['name', 'age', 'weight'],'formats': ['U30', 'i8', 'f8']}
填入dtype中即可
# 结构数组的取值方式和一般数组差不多,可以通过下标取得元素: >>>print(a[0]) ('ZhangSan', 25, 5) >>>print(a[-1]) ('WangWu', 24, 7) # 我们可以使用字段名作为下标获取对应的值 >>>print(a['name']) ['ZhangSan' 'LiSi' 'WangWu']