NumPy数组(9)-- 数组的转换

匿名 (未验证) 提交于 2019-12-03 00:29:01

tolist函数将Numpy中的数组转换为Python中的列表,还可以用astype指定转换数组的数据类型。

from numpy import *  #tolist astype  a = array([1,2,3,4,5,6]) print(a) print(a.tolist())    #将numpy中的数组转换为python中的列表 print("-----------------------1111--------------------------")  b = a.reshape(2,3) print(b) print(b.tolist()) print("-----------------------2222--------------------------")   a = array([1,2,3,4,5,'6']) print(a.astype(int))    #astype 能够指定数据类型 print("-----------------------3333--------------------------")  a = array([1,2,3,4,5,'x']) #print(a.astype(int))    #因为数组a中有字符串x,不能转换为int型,所以会抛出异常


输出结果:

[1 2 3 4 5 6] [1, 2, 3, 4, 5, 6] -----------------------1111-------------------------- [[1 2 3]  [4 5 6]] [[1, 2, 3], [4, 5, 6]] -----------------------2222-------------------------- [1 2 3 4 5 6] -----------------------3333-------------------------- 




易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!