numpy是一个在Python中做科学计算的基础库,重在数值计算,也是大部分Python科学计算库的基础库,多用于在大型、多维数组上执行数值运算
numpy创建数组(矩阵):
numpy中的数据类型:
数据类型的操作:
练习代码:
1 import random 2 import numpy as np 3 4 # 使用numpy生成数组,得到ndarray类型 5 t1 = np.array([1, 2, 3]) 6 print(t1) 7 print(type(t1)) 8 9 t2 = np.array(range(10)) 10 print(t2) 11 12 t3 = np.arange(4, 10, 2) 13 print(t3) 14 print(t3.dtype) 15 # dtype是numpy中的数据类型 16 t4 = np.arange(1, 4, dtype=float) 17 print(t4.dtype) 18 # numpy中的布尔类型 19 t5 = np.array([1, 0, 1, 0, 0], dtype=bool) 20 print(t5) 21 print(t5.dtype) 22 23 # 调整数据类型 24 t6 = t5.astype('int') 25 print(t6) 26 print(t6.dtype) 27 # numpy中的小数 28 t7 = np.array([random.random() for i in range(5)]) 29 print(t7) 30 print(t7.dtype) 31 32 t8 = np.round(t7, 2) 33 print(t8) 34 t9 = t7.round(2) 35 print(t9) 36 37 """输出结果 38 [1 2 3] 39 <class 'numpy.ndarray'> 40 [0 1 2 3 4 5 6 7 8 9] 41 [4 6 8] 42 int32 43 float64 44 [ True False True False False] 45 bool 46 [1 0 1 0 0] 47 int32 48 [0.73172751 0.08665029 0.86204468 0.45705802 0.83322977] 49 float64 50 [0.73 0.09 0.86 0.46 0.83] 51 [0.73 0.09 0.86 0.46 0.83] 52 """