@小结
numpy总结
numpy.array(object, dtype = None, copy = True, order = None, subok = False, ndmin = 0)
dt = np.dtype(np.int32)
dt = np.dtype('i4')
- object:数组或者数列
- dtype:数据类型 (int8, int16, int32, int64 四种数据类型可以使用字符串 ‘i1’, ‘i2’,‘i4’,‘i8’ 代替)
- copy:是否需要复制
- order:创建的数组样式,C为行,F为列
- subok:默认返回一个与基类类型一致的数组
- ndim:生成维度
数组属性
属性 | 介绍 |
---|---|
ndarray.ndim | 秩 即轴的数量或维度的数量 |
ndarray.shape | 数组的维度,对于矩阵,n 行 m 列 |
ndarray.size | 数组元素的总个数 |
ndarray.dtype | ndarray |
ndarray.itemsize | ndarray 对象中每个元素的大小,以字节为单位 |
ndarray.flags | ndarray 对象的内存信息 |
ndarray.real | ndarray元素的实部 |
ndarray.imag | ndarray 元素的虚部 |
ndarray.data | 包含实际数组元素的缓冲区,由于一般通过数组的索引获取元素所以通常不需要使用这个属性。 |
a=np.arange(10)
a.shape = (2,5)
b=a.reshape(2,5)
a
: array([[0, 1, 2, 3, 4],
[5, 6, 7, 8, 9]])
创建数组
numpy.empty(shape, dtype = float, order = 'C')
numpy.zeros(shape, dtype = float, order = 'C')
numpy.ones(shape, dtype = None, order = 'C')
numpy.arange(start, stop, step, dtype)
默认为浮点数
x = np.ones(5)
[1. 1. 1. 1. 1.]
- numpy.linspace一维等差数组:num个数
np.linspace(start, stop, num=50, endpoint=True, retstep=False, dtype=None)
a =np.linspace(1,10,10,retstep= True)
(array([ 1., 2., 3., 4., 5., 6., 7., 8., 9., 10.]), 1.0)
- numpy.logspace 函数用于创建一个于等比数列:
np.logspace(start, stop, num=50, endpoint=True, base=10.0, dtype=None)
a = np.logspace(0,9,10,base=2)
[ 1. 2. 4. 8. 16. 32. 64. 128. 256. 512.]
数组切片
a = np.array([[1,2,3],[3,4,5],[4,5,6]])
a[1:]
[[3 4 5]
[4 5 6]]
a[1,…] 表示第二行数据 == a[1]
数组索引
- 布尔索引
x = np.array([[ 0, 1, 2],[ 3, 4, 5]])
print(x[x>1])
[2 3 4 5]
~(取补运算符)
- 花式索引
花式索引指的是利用整数数组进行索引
目标是一维数组,那么索引的结果就是对应位置的元素
目标是二维数组,那么就是对应下标的行
它总是将数据复制到新数组中
x=np.arange(9).reshape((3,3))
print (x[[2,2,1,0]])
[[6 7 8]
[6 7 8]
[3 4 5]
[0 1 2]]
传入多个索引数组(要使用np.ix_)
x=np.arange(9).reshape((3,3))
print (x[[2,2,1,0],[1]])
[7 7 4 1]
x[np.ix_([1,5,7,2],[0,3,1,2])])
广播机制
- 让所有输入数组都向其中形状最长的数组看齐,形状中不足的部分都通过在前面加 1 补齐。
- 输出数组的形状是输入数组形状的各个维度上的最大值。
- 如果输入数组的某个维度和输出数组的对应维度的长度相同或者其长度为 1 时,这个数组能够用来计算,否则出错。
- 当输入数组的某个维度的长度为 1 时,沿着此维度运算时都用此维度上的第一组值。
数组操作
for x in np.nditer(a) 数组迭代器
for element in a.flat
numpy.ravel() 展平的数组元素