numpy 是一个在 Python 中做科学计算的基础库, 重在数值计算, 也是大部分 Python 科学计算库的基础库, 多用于在大型, 多维数组上执行数值运算
numpy 创建数组 (矩阵):
numpy 中的数据类型:
数据类型的操作:
练习代码:
- import random
- import numpy as np
- # 使用 numpy 生成数组, 得到 ndarray 类型
- t1 = np.array([1, 2, 3])
- print(t1)
- print(type(t1))
- t2 = np.array(range(10))
- print(t2)
- t3 = np.arange(4, 10, 2)
- print(t3)
- print(t3.dtype)
- # dtype 是 numpy 中的数据类型
- t4 = np.arange(1, 4, dtype=float)
- print(t4.dtype)
- # numpy 中的布尔类型
- t5 = np.array([1, 0, 1, 0, 0], dtype=bool)
- print(t5)
- print(t5.dtype)
- # 调整数据类型
- t6 = t5.astype('int')
- print(t6)
- print(t6.dtype)
- # numpy 中的小数
- t7 = np.array([random.random() for i in range(5)])
- print(t7)
- print(t7.dtype)
- t8 = np.round(t7, 2)
- print(t8)
- t9 = t7.round(2)
- print(t9)
- """ 输出结果
- [1 2 3]
- <class 'numpy.ndarray'>
- [0 1 2 3 4 5 6 7 8 9]
- [4 6 8]
- int32
- float64
- [ True False True False False]
- bool
- [1 0 1 0 0]
- int32
- [0.73172751 0.08665029 0.86204468 0.45705802 0.83322977]
- float64
- [0.73 0.09 0.86 0.46 0.83]
- [0.73 0.09 0.86 0.46 0.83]
- """
来源: http://www.bubuko.com/infodetail-3119095.html