【python】numpy库ndarray多维数组的类型变换 .astype()与向列表的转换tolist()详解与实例

时间:2020-11-26 16:05:57

1、ndarray数组的类型变换np. astype(dtype)

astype()方法一定会创建新的数组(原始数据的一个拷贝),即使两个类型一致

In [30]: a
Out[30]:
array([[ 0, 1, 2, 3, 4], [ 5, 6, 7, 8, 9], [10, 11, 12, 13, 14], [15, 16, 17, 18, 19]])

In [31]: new_a = a.astype(dtype = np.float16)

In [32]: new_a
Out[32]:
array([[ 0., 1., 2., 3., 4.], [ 5., 6., 7., 8., 9.], [ 10., 11., 12., 13., 14.], [ 15., 16., 17., 18., 19.]], dtype=float16)

2、ndarray数组向列表的转换np.tolist()

In [33]: new_a.tolist()
Out[33]:
[[0.0, 1.0, 2.0, 3.0, 4.0], [5.0, 6.0, 7.0, 8.0, 9.0], [10.0, 11.0, 12.0, 13.0, 14.0], [15.0, 16.0, 17.0, 18.0, 19.0]]