numpy是一个开源的Python计算库,包括了很多数学函数。numpy的主要功能之一是用来操作数组与矩阵。也有人说Python+numpy=matable。
numpy里基本数据都是ndarray(N-dimensional array)类型的。
#导入numpy
>>>import numpy as np
>>>a = [1,2,3,4,5,6,7,8,9]
>>>print(a)
>>>a * 2 #把每个列表重复一遍,而不是数值乘以2

想要对列表的数值乘以2可以通过循环来实现,也可以通过把list转换成ndarray的方法来实现。
#把普通Python中的list转换成ndarray,这样就不用写循环来进行数值运算了,可以直接用这个方法。
>>>A = np.array(a)
>>>print(A)
>>>A
[1 2 3 4 5 6 7 8 9]
array([1, 2, 3, 4, 5, 6, 7, 8, 9])
>>>print(type(A))
<class 'numpy.ndarray'>
数组运算:
#指定维度来创建多维数组
>>>e = np.array([1,2,3,4,5,6],ndmin=3)
>>>print(e)
[[[1 2 3 4 5 6]]]
#指定维度和数值类型来创建多维数组
>>>f = np.array([1,2,3,4,5,6],ndmin=3,dtype=np.complex) #dtype里的“np.”不能省略
>>>print(f)
[[[1.+0.j 2.+0.j 3.+0.j 4.+0.j 5.+0.j 6.+0.j]]]
ndarry里有一些基本类型
属性 | 描述 |
---|---|
ndarray.ndim | 数组轴的个数,也被称作秩 |
ndarray,shape | 数组在每个维度上大小的整数元组 |
ndarray,size | 数组元素的总个数 |
ndarray.dtype | 数组元素的数据类型,dtype 类型可以用于创建数组中 |
ndarray.itemsize | 数组中每个元素的字节大小 |
ndarray.data | 包含实际数组元素的缓冲区地址 |
ndarray,flat | 数组元素的迭代器 |
可以通过修改数组的shape属性,在保持数组元素个数不变的情况下,改变数组每个轴的长度。
>>>g = np.array([[1,2,3,4],[4,5,6,7],[7,8,9,10]])
>>>print(g)
>>>g.shape = 4,3
>>>print(g)
注意从(3,4)改为(4,3)并不是对数组进行转置,而只是改变每个轴的大小,数组元素在内存中的位置并没有改变。
>>>g.shape = 2,-1
>>>print(g)
[[ 1 2 3 4 4 5]
[ 6 7 7 8 9 10]]
当某个轴的元素为-1时,将根据数组元素的个数自动计算此轴的长度。
>>>h = g.reshape(6,2)
>>>print(h)
[[ 1 2]
[ 3 4]
[ 4 5]
[ 6 7]
[ 7 8]
[ 9 10]]
使用数组的reshape方法,可以创建一个改变了尺寸的新数组,原数组的shape保持不变