Numpy数据类型转换astype,dtype

1、查看数据类型、转换数据类型

 
 
In [11]: arr = np.array([1,2,3,4,5])

In [12]: arr
Out[12]: array([1, 2, 3, 4, 5])

// 该命令查看数据类型
In [13]: arr.dtype
Out[13]: dtype('int64')

//  转换数据类型 int64 -> float64 
In [14]: float_arr = arr.astype(np.float64)

// 该命令查看数据类型
In [15]: float_arr.dtype
Out[15]: dtype('float64')

2、字符串数组转换为数值型

In [4]: numeric_strings = np.array(['1.2','2.3','3.2141'], dtype=np.string_)

In [5]: numeric_strings
Out[5]: array(['1.2', '2.3', '3.2141'], dtype='|S6')

// 此处写的是float 而不是np.float64, Numpy很聪明,会将python类型映射到等价的dtype上
In [6]: numeric_strings.astype(float)
Out[6]: array([ 1.2, 2.3, 3.2141])

猜你喜欢

转载自blog.csdn.net/zio123/article/details/79462838
今日推荐