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'

 

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值