在 NumPy 中,数组转换有两种方式,一种是将数组转换成列表,另一种就是转换数组的数据类型。本节教程就对这两种数组转换进行详细介绍。
数组转换成列表
将数组转换成列表用 tolist() 函数,使用 tolist() 函数的方法如下:
数组名.tolist()
示例代码如下。
# -*- coding: UTF-8 -*-
import numpy as np
#创建3行3列的数组arr
arr = np.arange(9).reshape(3,3)
print('原数组:',arr)
print('将arr数组转换成列表')
arr_list = arr.tolist() #转换成列表为[[0, 1, 2], [3, 4, 5], [6, 7, 8]]
print(arr_list)
数组的数据类型转换
数组有一个 dtype 属性,通过该属性可以查看数组的数据类型,方法是数组名.dtype。而数组的数据类型在创建数组时就已经通过 dtype 参数确定了,如果想实现数组中数值类型的转换可采用 astype() 函数。
astype() 函数的格式如下:
数组名.astype(numpy.数据类型)
astype() 函数应用示例代码如下。
# -*- coding: UTF-8 -*-
import numpy as np
float_arr = np.array([1.2, 2.1, 4.5, 6.3]) #创建浮点数数组
print(float_arr.dtype) #查看当前数据类型
#将float转换为int时,小数部分被舍弃
int_arr = float_arr.astype(np.int32)
print (int_arr,int_arr.dtype)
#把字符串转换为数组,如果字符串不是数字字符串,则会抛出异常
str_arr = np.array(['2.35', '-7.6', '23'], dtype = np.string_)
float_arr = str_arr.astype(dtype = np.float)
print (float_arr,float_arr.dtyp
注意:复数不能转换为整数,也不能转换为浮点数,但是可以转换为复数。