ndarray 的数据类型

In [24]: arr1 = np.array([1, 2, 3], dtype = np.float64)

In [25]: arr2 = np.array([1, 2, 3], dtype = np.int32)

In [26]: arr1
Out[26]: array([1., 2., 3.])

In [27]: arr2
Out[27]: array([1, 2, 3])

In [28]: arr1.dtype
Out[28]: dtype('float64')

In [29]: arr2.dtype
Out[29]: dtype('int32')

使用 astype 方法显示地转换数组的数据类型。

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

In [31]: arr.dtype
Out[31]: dtype('int32')

In [32]: float_arr = arr.astype(np.float64)

In [33]: float_arr
Out[33]: array([1., 2., 3., 4., 5.])

In [34]: float_arr.dtype
Out[34]: dtype('float64')
In [35]: arr = np.array([3.7, -1.2, -2.6, 0.5, 12.9, 10.1])

In [36]: arr
Out[36]: array([ 3.7, -1.2, -2.6,  0.5, 12.9, 10.1])

In [37]: arr.astype(arr.int64)
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
 in 
----> 1 arr.astype(arr.int64)

AttributeError: 'numpy.ndarray' object has no attribute 'int64'

In [38]: arr.astype(np.int64)
Out[38]: array([ 3, -1, -2,  0, 12, 10], dtype=int64)

如果数组中元素是数字含义的字符串,可通过 astype 将字符串转换为数字。

In [41]: numeric_strings = np.array(['1.22', '-9.6', '42'], dtype = np.string_)

In [42]: numeric_strings.astype(float)
Out[42]: array([ 1.22, -9.6 , 42.  ])

可以使用另一个数字的 dtype 属性。

In [44]: int_array = np.arange(10)

In [45]: calibers = np.array([.22, .270, .357, .380, .44, .50], dtype = np.float64)

In [46]: calibers
Out[46]: array([0.22 , 0.27 , 0.357, 0.38 , 0.44 , 0.5  ])

In [47]: int_array.astype(calibers.dtype)
Out[47]: array([0., 1., 2., 3., 4., 5., 6., 7., 8., 9.])

也可使用类型代码来传入数据类型。

In [48]: empty_uint32 = np.empty(8, dtype = 'u4')

In [49]: empty_uint32
Out[49]:
array([         0, 1072693248,          0, 1072693248,          0,
       1072693248,          0, 1072693248], dtype=uint32)

使用 astype 时总是生成一个新数组。

你可能感兴趣的:(ndarray 的数据类型)