# Numpy数据类型对象详细指南

2021年3月17日17:01:46 发表评论 746 次浏览

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

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

``````# 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``````

``````# 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])

``````('John', [ 6.,  7.])