函数 | 说明 |
type() | 返回数据结构类型(list、dict、numpy.ndarray 等) |
dtype() | 返回数据元素的数据类型(int、float等) 备注: 1)由于 list、dict 等可以包含不同的数据类型,因此不可调用dtype()函数 2)np.array 中要求所有元素属于同一数据类型,因此可调用dtype()函数 |
astype() | 改变np.array中所有数据元素的数据类型。 备注:能用dtype() 才能用 astype() |
a1 = [2.2, 1.6, 2.3, 6.4, 6.2]
print(type(a1))
print(a1.dtype)
-----输出结果 -------
<class 'list'>
File "D:/tf36/delete02.py", line 11, in <module>
print(a1.dtype)
AttributeError: 'list' object has no attribute 'dtype'
可以看出,虽说list 这种python自带的数据类型, 虽说你内部的数据类型相同 都是float 类型,但是它却也是
不可以调用 dtype 这个方法的。
import numpy as np
b1 = np.array(a1)
print(type(b1))
print(b1.dtype)
--------------- 输出结果 ---------------
<class 'numpy.ndarray'>
float64
这也就意味着 ndarray 类型的数组 , 其内部的数据类型都是相同的, 所以可以使用 dtype 方法
然后, 根据上表当中说到的, 可以使用 dtype 的数据类型才可以使用 astype
import numpy as np
a1 = [2.2, 1.6, 2.3, 6.4, 6.2]
b1 = np.array(a1)
c1 = b1.astype('int32')
print(c1)
print(type(c1))
print(c1.dtype)
————————————————输出结果 ————————————————————————
[2 1 2 6 6]
<class 'numpy.ndarray'>
int32
ok