浅谈python 中的 type(), dtype(), astype()的区别
如下所示:
返回数据元素的数据类型(int、float等)
备注:1)由于list、dict等可以包含不同的数据类型,因此不可调用dtype()函数
2)np.array中要求所有元素属于同一数据类型,因此可调用dtype()函数
改变np.array中所有数据元素的数据类型。
备注:能用dtype()才能用astype()
测试代码:
importnumpyasnp
classMyclass():
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))
print("type(b)=",type(b))
print("type(c)=",type(c))
print("type(d)=",type(d))
print("type(e)=",type(e))
print("type(f)=",type(f))
print("type(c_)=",type(c_))
#print(a.dtype)##AttributeError:'list'objecthasnoattribute'dtype'
#print(b.dtype)##AttributeError:'dict'objecthasnoattribute'dtype'
print(c.dtype)
#print(d.dtype)##AttributeError:'Myclass'objecthasnoattribute'dtype'
print(e.dtype)
print(c_.dtype)
#print(f.dtype)##AttributeError:'int'objecthasnoattribute'dtype'
#print(a.astype(np.int))##AttributeError:'list'objecthasnoattribute'astype'
#print(b.astype(np.int))##AttributeError:'dict'objecthasnoattribute'astype'
print(c.astype(np.int))
#print(d.astype(np.int))##AttributeError:'Myclass'objecthasnoattribute'astype'
print(e.astype(np.int))
#print(f.astype(np.int))##AttributeError:'int'objecthasnoattribute'astype'
补充知识:pandasastype()错误
由于数据出现错误
DataError:Nonumerictypestoaggregate
改正以后才认识到astype的重要性。
Top15['populations']=Top15['EnergySupply'].div(Top15['EnergySupplyperCapita']).astype(float)
df_mean=((df.set_index('Continent').groupby(level=0)['populations'].agg({'mean':np.mean})))
#加了astype(float)后无错误
以上这篇浅谈python中的type(),dtype(),astype()的区别就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持毛票票。