Python 中的 type(), dtype(), astype()的区别

函数 说明
type() 返回数据结构类型(list、dict、numpy.ndarray 等)
dtype() 返回数据元素的数据类型(int、float等)
备注:1)由于 list、dict 等可以包含不同的数据类型,因此不可调用dtype()函数

2)np.array 中要求所有元素属于同一数据类型,因此可调用dtype()函数
astype() 改变np.array中所有数据元素的数据类型。

备注:能用dtype() 才能用 astype()
import numpy as np
class Myclass():
pass

a = [[1,2,3],[4,5,6]]
b = {'a':1,'b':2,'c':3}
c = np.array([1,2,3])
d = Myclass()
e = np.linspace(1,5,10)
c_ = c.astype(np.float)
f = 10

print("type(a)=", type(a)) # type(a)= <class 'list'>
print("type(b)=", type(b)) # type(b)= <class 'dict'>
print("type(c)=", type(c)) # type(c)= <class 'numpy.ndarray'>
print("type(d)=", type(d)) # type(d)= <class '__main__.Myclass'>
print("type(e)=", type(e)) # type(e)= <class 'numpy.ndarray'>
print("type(f)=", type(f)) # type(f)= <class 'int'>
print("type(c_)=", type(c_)) # type(c_)= <class 'numpy.ndarray'>



# print(a.dtype) ## AttributeError: 'list' object has no attribute 'dtype'
# print(b.dtype) ## AttributeError: 'dict' object has no attribute 'dtype'
print(c.dtype) ## int32
# print(d.dtype) ## AttributeError: 'Myclass' object has no attribute 'dtype'
print(e.dtype) ## float64
print(c_.dtype) ## float64
# print(f.dtype) ## AttributeError: 'int' object has no attribute 'dtype'

# print(a.astype(np.int)) ## AttributeError: 'list' object has no attribute 'astype'
# print(b.astype(np.int)) ## AttributeError: 'dict' object has no attribute 'astype'
print(c.astype(np.int)) ## [1 2 3]
# print(d.astype(np.int)) ## AttributeError: 'Myclass' object has no attribute 'astype'
print(e.astype(np.int)) ## [1 1 1 2 2 3 3 4 4 5]
# print(f.astype(np.int)) ## AttributeError: 'int' object has no attribute 'astype'

下面的示例定义一个结构化数据类型 student,包含字符串字段 name,整数字段 age,及浮点字段 marks,并将这个 dtype 应用到 ndarray 对象。

import numpy as np
student = np.dtype([('name','S20'), ('age', 'i1'), ('marks', 'f4')])
print(student)

输出结果为:

[('name', 'S20'), ('age', 'i1'), ('marks', 'f4')]
import numpy as np
student = np.dtype([('name','S20'), ('age', 'i1'), ('marks', 'f4')])
a = np.array([('abc', 21, 50),('xyz', 18, 75)], dtype = student)
print(a)

输出结果为:

[('abc', 21, 50.0), ('xyz', 18, 75.0)]

参考链接:

https://blog.csdn.net/Strive_For_Future/article/details/92811293

https://www.runoob.com/numpy/numpy-dtype.html