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()

 

 

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 

 

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值