numpy数据类型
(1)如何看数据类型
使用dtype来查看数据类型,如:
import numpy as np
n1 = np.arange(10)
print(n1)
print(n1.dtype)
[0 1 2 3 4 5 6 7 8 9]
int32
(2)numpy中有哪些数据类型
numpy是基于c语言写出来的,所以numpy中的整形和c语言中相同。
有int8,int16,int32,int64,int8 指的是8bit,相当于一个字节(Byte)。
有bool类型
有uint类型代表无符号整形
有float类型
有complex类型
有object类型,表示python中的对象等等
n2 = np.array([1,2,3,4,5],dtype = np.int8)
如果你知道数组里的数组范围,可以指定他们的类型;如上,将其指定为int8类型
class Student:
def __init__(self,name,grade):
self.name = name
self.grade = grade
n3 = np.array([Student('李',648),Student('张',404)])
print(n3)
print(n3.dtype)
[<__main__.Student object at 0x000002B66F96C190>
<__main__.Student object at 0x000002B66F96CCA0>]
object
以上是将数组里面的内容设置为对象
(3)数据类型的转换(ndarray.astype)
以下将int转化为double
n4 = np.array([1,2,3,4],dtype = np.int8)
n5 = n4.astype(np.double)
print(n4.dtype)
print(n5.dtype)
int8
float64
以下是将字符串转为unicode类型
n6 = np.array(['ab','cd','ef'],dtype="S")
print(n6.dtype)
n7 = n6.astype("U")
print(n7.dtype)
|S2
<U2