可以利用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--------------------------