Numpy数据类型转化astype,dtype

1. 查看数据类型

import numpy as np
arr = np.array([1,2,3,4,5])
print(arr)
[1 2 3 4 5]
# dtype用来查看数据类型
arr.dtype
dtype('int32')

2. 转换数据类型

# astype用来转换数据类型
float_arr = arr.astype(np.float64)
# dtype用来查看数据类型
float_arr.dtype
dtype('float64')
# 将浮点数转换为整数,小数部分会被截断
arr2 = np.array([1.1, 2.2, 3.3, 4.4, 5.3221])
print(arr2)
arr3 = arr2.astype(np.int32)
print(arr3)
[ 1.1     2.2     3.3     4.4     5.3221]
[1 2 3 4 5]

 

3. 字符串数组转换为数值型

# 字符数组转换为数值型
numeric_strings = np.array(['1.1', '2.3', '3.2141'], dtype=np.string_)
numeric_strings 
array([b'1.1', b'2.3', b'3.2141'],
      dtype='|S6'
# 此处用float而不是np.float64,Numpy会将python类型映射到等价的dtype上
numeric_strings.astype(float)
array([ 1.1   ,  2.3   ,  3.2141])

 

 

来自:silent彦沁

 

posted @ 2019-07-16 20:26  做梦当财神  阅读(9564)  评论(0编辑  收藏  举报