A-A+
Python NumPy数组元素类型转换函数astype
在Python中可以使用NumPy中的astype方法来转换数组中元素的类型,此方法的格式如下:
matrix.astype(dtype, order='K', casting='unsafe', subok=True, copy=True)
其中dtype用来指定要转换成的数据类型,数组中的所有元素都会被转换。示例代码:
- >>> A=np.array([[1,1.2],[1.5,-1.8],[0,-1.2]])
- >>> A.astype(int)
- array([[ 1, 1],
- [ 1, -1],
- [ 0, -1]])
- >>> B=np.array([-1,2,3.8])
- >>> C=B>0
- >>> C.astype(int)
- array([0, 1, 1])