Python:type()、dtype()、astype()、ndim()、shape()、size() 的用法

1 type/dtype/astype

Python中与数据类型相关函数及属性有如下三个:type/dtype/astype。

名称描述
type()返回参数的数据类型
dtype返回数组中元素的数据类型
astype()对数据类型进行转换

1.1 type()

type()用于获取数据类型。

# type用于获取数据类型
import numpy as np

a=[1,2,3]
print(type(a))

#>>><class 'list'>

b=np.array(a)
print(type(b))

#>>><class 'numpy.ndarray'>

1.2 dtype

dtype用于获取数组中元素的类型。

# dtype用于获取数组中元素的类型

print(b.dtype)

#>>>int64

x,y,z=1,2,3
c=np.array([x,y,z])
print(c.dtype)

#>>>int64

d=np.array([1+2j,2+3j,3+4j])
print(d.dtype)

#>>>complex128

1.3 astype()

astype()修改数据类型。

#astype修改数据类型

e=np.linspace(1,5,20)
print(e)

#>>>
'''
[1.         1.21052632 1.42105263 1.63157895 1.84210526 2.05263158
 2.26315789 2.47368421 2.68421053 2.89473684 3.10526316 3.31578947
 3.52631579 3.73684211 3.94736842 4.15789474 4.36842105 4.57894737
 4.78947368 5.        ]
'''
print(e.dtype)

#>>>float64

e=e.astype(int)
print(e)

#>>>[1 1 1 1 1 2 2 2 2 2 3 3 3 3 3 4 4 4 4 5]

print(e.dtype)

#>>>int64

2 ndim/shape/size

2.1 ndim

ndim用于获取数据的维度。

import numpy as np

a=np.array([1,2,3])
print(a.ndim)

# result
1

b=np.array([[1,2,3],[4,5,6],[7,8,9]])
print(b.ndim)

# result
2

c=np.array([[[1,2,3],[4,5,6],[7,8,9]]])
print(c.ndim)

# result
3

2.2 shape

shape描述的是矩阵的形状。

import numpy as np

a=np.array([1,2,3])
print(a.shape)

# result
3

b=np.array([[1,2,3],[4,5,6],[7,8,9]])
print(b.shape)

# result
(3,3)

c=np.array([[[1,2,3],[4,5,6],[7,8,9]]])
print(c.shape)

# result
(1,3,3)  #(H,W,C)

2.3 size

size描述的是元素的个数。

import numpy as np

a=np.array([1,2,3])
print(a.shape)

# result
3

b=np.array([[1,2,3],[4,5,6],[7,8,9]])
print(b.shape)

# result
9

c=np.array([[[1,2,3],[4,5,6],[7,8,9]]])
print(c.shape)

# result
9  

参考:https://blog.csdn.net/MsSpark/article/details/83831474

 

 

 

 

 

 

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值