1.简介:
numpy支持大规模矩阵运算,同时提供大量数组运算的数学函数
特点:
N维数组对象ndarray
广播功能
嵌入线性代数,傅里叶变换,随机数生成等功能函数
整合了C/C++/Fortran代码的工具
2.创建ndarray数组
语法1
numpy.array(object, dtype = None, copy = True, order = None, subok = False, ndim = 0)
object | 数组或嵌套的数列 |
dtype | 元素数据类型 |
copy | 对象是否需要复制 |
order | 创建数组的样式,C为行,F为列,A为任意 |
subok | 默认返回一个和基类类型一致的数组 |
ndmin | 指定生成数组的最小维度 |
import numpy as np
a1 = np.array([1, 2, 3])
print(a1)
a2 = np.array([[1, 2], [3, 4]])
print(a2)
a3 = np.array([1, 2, 3, 4], ndmin=2)
print(a3)
a4 = np.array([1 + 1j, 2 + 2j, 3], dtype=complex)
print(a4)
输出结果:
[1 2 3]
[[1 2]
[3 4]]
[[1 2 3 4]]
[1.+1.j 2.+2.j 3.+0.j]
语法2
numpy.zeros(shape, dtype = float, order = 'C')
创建元素都为0的数组
numpy.ones(shape, dtype = float, order = 'C')
创建元素都为1的数组
numpy.empty(shape, dtype = float, order = 'C')
shape | 数组形状 |
dtype | 数据类型 |
order | 'C'表示行优先,'F'表示列优先(指在计算机内存存储元素的顺序) |
a = np.zeros(10, dtype=np.float32)
print(a)
b = np.ones(10)
print(b)
c = np.empty((2, 2))
print(c)
输出结果:
[0. 0. 0. 0. 0. 0. 0. 0. 0. 0.]
[1. 1. 1. 1. 1. 1. 1. 1. 1. 1.]
[[9.90263869e+067 8.01304531e+262]
[2.60799828e-310 1.97643480e-077]]
语法3
numpy.asarray(a, dtype=None, order=None)
将输出转为一个数组
a:任意形式的输入参数,可以是,列表,列表的元组,元组,元组的元组,元组的列表,多维数组
x = [1, 2, 3]
y = ['a', 'b', 'c']
xx = np.asarray(x)
print(xx)
z = [x, y] #x, y都是list,满足其条件
zz = np.asarray(z)
print(zz)
输出结果
[1 2 3]
[['1' '2' '3']
['a' 'b' 'c']]
语法4
numpy.fromfile(filename, dtype=float, count=-1, offset=0)
使用已知数据类型读取二进制数据的高效方法,以及解析简单格式化的文本文件。
filename | 文件名或路径 |
dtype | 数据类型 |
count | 读取的数据数量。默认为-1,读取所有数据 |
offset | 读取的起始位置,默认为0 |
file = '123.dat'
a = np.fromfile(file, dtype=np.int16)
a = a.reshape(-1, 12)
print(a)
语法5
numpy.fromiter(iterable, type, count=-1)
从可迭代对象创建一个新的一维数组。
list = range(4)
it = iter(list)
x = np.fromiter(it, dtype=float)
print(x)
iterable = (i*i for i in range(4))
y = np.fromiter(iterable, float)
print(y)
输出结果:
[0. 1. 2. 3.]
[0. 1. 4. 9.]
语法6
numpy.arange(start=0, stop, step=1, dtype=None)
在给定的间隔内返回均匀间隔的值。
输出[start, stop-1],间隔step
x = np.arange(1, 10)
y = np.arange(1, 10, 2)
print(x)
print(y)
输出结果:
[1 2 3 4 5 6 7 8 9]
[1 3 5 7 9]
语法7
numpy.linspace(start, stop, num = 50, endpoint = True, restep = False, dtype = None)
在指定的间隔内返回均匀间隔的数字。和arange很像
start | 起始值 |
stop | 终止值 |
num | 需要生成的等步长的样本数量,默认50 |
endpoint | 默认为True,指序列包括stop值 |
retstep | 若为True,生成的数组会显示间距 |
dtype | 数据类型 |
x = np.linspace(0, 10, 20)
print(x)
y = np.linspace(0, 10, 20, retstep=True)
print(y)
输出结果:
[ 0. 0.52631579 1.05263158 1.57894737 2.10526316 2.63157895
3.15789474 3.68421053 4.21052632 4.73684211 5.26315789 5.78947368
6.31578947 6.84210526 7.36842105 7.89473684 8.42105263 8.94736842
9.47368421 10. ]
(array([ 0. , 0.52631579, 1.05263158, 1.57894737, 2.10526316,
2.63157895, 3.15789474, 3.68421053, 4.21052632, 4.73684211,
5.26315789, 5.78947368, 6.31578947, 6.84210526, 7.36842105,
7.89473684, 8.42105263, 8.94736842, 9.47368421, 10. ]), 0.5263157894736842)
语法8
numpy.logspace(start, stop, num = 50, endpoint = True, base = 10.0, dtype = None)
返回在对数刻度上均匀间隔的数字。
x = np.logspace(1.0, 3.0, num=5)
print(x)
输出结果:
[ 10. 31.6227766 100. 316.22776602 1000. ]
3.ndarray数组属性
ndim | 维数 |
shape | 数组的维度 |
size | 元素的总个数 |
dtype | 元素类型 |
itemsize | 每个元素的大小,字节为单位 |
flags | 内存信息 |
real | 实部 |
imag | 虚部 |
x = np.arange(12)
print(x)
print('ndim:', x.ndim)
y = x.reshape(2,2,3)
print(y)
print('ndim:', y.ndim)
print('size:', y.size)
print('shape:', y.shape)
print('itemsize:', y.itemsize)
输出结果:
[ 0 1 2 3 4 5 6 7 8 9 10 11]
ndim: 1
[[[ 0 1 2]
[ 3 4 5]]
[[ 6 7 8]
[ 9 10 11]]]
ndim: 3
size: 12
shape: (2, 2, 3)
itemsize: 4
4.数组操作
1.切片和索引
语法结构
1.arrayname[slice(start, stop, step)]
2.arrayname[start:stop:step]
a = np.arange(24)
print(a[9])
s = slice(1, 9, 2) # start, stop, step
print(a[s])
b = a[1:9:2]
print(b)
输出结果:
9
[1 3 5 7]
[1 3 5 7]
2.高级索引
数组索引 ndarray[[row_list], [col_list]]
布尔索引 ndarray[ndarray>c]
花式索引 ndarray[整数数组]
a = np.arange(32).reshape(8, 4)
print(a)
print(a[[0, 1, 2], [0, 1, 2]]) # 数组索引
print(a[a < 15]) # 布尔索引
print(a[[1, 3, 6, 7]]) # 花式索引
输出结果:
[[ 0 1 2 3]
[ 4 5 6 7]
[ 8 9 10 11]
[12 13 14 15]
[16 17 18 19]
[20 21 22 23]
[24 25 26 27]
[28 29 30 31]]
[ 0 5 10]
[ 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14]
[[ 4 5 6 7]
[12 13 14 15]
[24 25 26 27]
[28 29 30 31]]
3.广播操作
先满足低维,再满足高维(从右至左)。数据沿轴平铺
a = np.arange(12).reshape(4, 3)
b = np.array([0, 1, 2])
print(a + b)
输出结果:
[[ 0 2 4]
[ 3 5 7]
[ 6 8 10]
[ 9 11 13]]
4.修改数组形状
reshape | 不改变数据,修改形状 |
flat | 数组元素迭代器 |
flatten | 返回一份数组拷贝,对拷贝所作的修改不会影响原始数组 |
ravel | 返回展开数组 |
a = np.arange(12).reshape(3, 4)
print('origin:')
print(a)
print('iter:')
for element in a.flat:
print(element, end=' ')
b = a.flatten()
print('\n数组拷贝:')
print(b)
print('展开数组:')
print(a.ravel())
输出结果:
origin:
[[ 0 1 2 3]
[ 4 5 6 7]
[ 8 9 10 11]]
iter:
0 1 2 3 4 5 6 7 8 9 10 11
数组拷贝:
[ 0 1 2 3 4 5 6 7 8 9 10 11]
展开数组:
[ 0 1 2 3 4 5 6 7 8 9 10 11]
5.翻转数组
transpose | 转置 |
T | 也是转置 |
rollaxis | 向后滚动指定的轴 |
swapaxes | 对换数组的两个轴 |
a = np.arange(12).reshape(3, 4)
print('origin:')
print(a)
print('transpose1:')
print(np.transpose(a))
print('transpose2:')
print(a.T)
输出结果:
origin:
[[ 0 1 2 3]
[ 4 5 6 7]
[ 8 9 10 11]]
transpose1:
[[ 0 4 8]
[ 1 5 9]
[ 2 6 10]
[ 3 7 11]]
transpose2:
[[ 0 4 8]
[ 1 5 9]
[ 2 6 10]
[ 3 7 11]]
6.连接数组
concatenate | 连接沿现有轴的数组 |
stack | 沿着新的轴加入一系列数组 |
hstack | 水平堆叠序列中的数组(各列数据增加) |
vsatck | 竖直堆叠序列中的数组(各行数据增加) |
7.数学函数
三角函数
算术运算的函数:add(), substract(), multiply(), divide()
统计函数:amin(), amax(), ptp(), median(), mean()
复数处理函数
a = np.array([[1, 3], [4, 2]])
print(np.sum(a, axis=1, keepdims=True)) # 按行相加,keepdims=True指保持其二维特性
print(np.sum(a, axis=1)) # 按行相加,默认不保持其二维特性
输出结果:
[[4]
[6]]
[4 6]
文件操作
1.save操作
numpy.save(file, arr, allow_pickle=True, fix_imports=True)
a = np.arange(10)
np.save('out.py', a)
数据保存在out.py文件内
2.savetext操作
np.loadtxt(file, dtype=int, delimeter=' ')
np.savetxt(file, a, fmt="%d", delimeter=",")
a = np.arange(10)
np.savetxt('out.txt', a)
b = np.loadtxt('out.txt')
print(b)