Numpy数值处理
一个在Python中做科学计算的基础库,重在数值计算,也是大部分python科学计算库的基础库,多用在大型、多维数组上执行数值运算
01 数组的属性
1. 数组类型+类型转化:
import random
import numpy as np
# numpy的数组类型 <class 'numpy.ndarray'>
# numpy对数组中数据的类型t1.dtype: int64 (与电脑位数有关)
# 生成数组的多种方法
t1 = np.array([1, 2, 3, 4, 5])
t2 = np.array(range(10))
t3 = np.arange(10)
# 可以通过dtype指定数据类型
t4 = np.array(range(1, 4), dtype="i1")
# 调整数据类型
t6 = t4.astype("int8")
# numpy中的小数
t7 = np.array([random.random() for i in range(10)])
# decimals改变小数位数
t8 = np.round(t7, 2)
2. 数组的形状:
import numpy as np
t1 = np.arange(12)
t2 = np.array([[1, 2, 3], [4, 5, 6]])
t3 = np.array([[[1, 2, 3], [4, 5, 6]], [[7, 8, 9], [10, 11, 12]]])
# reshape会返回一个新数组的视图,但是不会改变原数组
# 3行4列
t1 = t1.reshape((3, 4))
t5 = t1.reshape((t1.shape[0] * t1.shape[1],))
# 将数组转化成一维数组 flatten()
t5.flatten()
# reshape的形参:块数:2,每块行数:3,每块列数:4
t4 = np.arange(24).reshape((2, 3, 4)

最低0.47元/天 解锁文章
1044





