# NumPy Python中的数据类型对象（dtype）

2021年3月20日16:56:34 发表评论 391 次浏览

• 数据类型(整数, 浮点数, Python对象等)
• 数据大小(字节数)
• 数据的字节顺序(小端或大端)
• 如果数据类型是子数组, 则其形状和数据类型是什么。

ndarray的值存储在缓冲区中, 可以将其视为内存字节的连续块。因此, 如何解释这些字节由dtype对象给出。

• obj：要转换为数据类型对象的对象。
• 对齐：bool, 可选
在字段中添加填充以匹配C编译器将为类似的C结构输出的内容。
• 复制：bool, 可选
制作数据类型对象的新副本。如果为False, 则结果可能只是对内置数据类型对象的引用。
``````# Python Program to create a data type object
import numpy as np

# np.int16 is converted into a data type object.
print (np.dtype(np.int16))``````

``int16``
``````# Python Program to create a data type object
# containing a 32 bit big-endian integer
import numpy as np

# i4 represents integer of size 4 byte
# > represents big-endian byte ordering and < represents little-endian encoding.
# dt is a dtype object
dt = np.dtype( '>i4' )

print ( "Byte order is:" , dt.byteorder)

print ( "Size is:" , dt.itemsize)

print ( "Data type is:" , dt.name)``````

``````Byte order is: >
Size is: 4
Name of data type is: int32``````

1. b1, i1, i2, i4, i8, u1, u2, u4, u8, f2, f4, f8, c8, c16, a
(代表字节, 整数, 无符号整数, 浮点数, 复数和
指定的固定长度字符串字节长度)
2. int8, …, uint8, …, float16, float32, float64, complex64, complex128
(这次与一点尺寸)

``dtype is different from type. ``
``````# Python program to differentiate
# between type and dtype.
import numpy as np

a = np.array([ 1 ])

print ( "type is: " , type (a))
print ( "dtype is: " , a.dtype)``````

``````type is:
dtype is:  int32``````

``````# Python program for demonstrating
# the use of fields
import numpy as np

# A structured data type containing a 16-character string (in field ‘name’)
# and a sub-array of two 64-bit floating-point number (in field ‘grades’):

dt = np.dtype([( 'name' , np.unicode_, 16 ), ( 'grades' , np.float64, ( 2 , ))])

# Data type of object with field grades

# Data type of object with field name
print (dt[ 'name' ])``````

``('<f8', (2, ))``
``````# Python program to demonstrate
# the use of data type object with structured array.
import numpy as np

dt = np.dtype([( 'name' , np.unicode_, 16 ), ( 'grades' , np.float64, ( 2 , ))])

# x is a structured array with names and marks of students.
# Data type of name of the student is np.unicode_ and
# data type of marks is np.float(64)
x = np.array([( 'Sarah' , ( 8.0 , 7.0 )), ( 'John' , ( 6.0 , 7.0 ))], dtype = dt)

print (x[ 1 ])
print ( "Grades of John are: " , x[ 1 ][ 'grades' ])
print ( "Names are: " , x[ 'name' ])``````

``````('John', [ 6.,  7.])
Grades of John are:  [ 6.  7.]
Names are:  ['Sarah' 'John']``````

• docs.scipy.org
• 结构化数组