Numpy数据类型对象详细指南

【Numpy数据类型对象详细指南】每个ndarray都有一个关联的数据类型(dtype)对象。此数据类型对象(dtype)通知我们有关数组的布局。这意味着它为我们提供了有关以下信息:

  • 数据类型(整数, 浮点数, Python对象等)
  • 数据大小(字节数)
  • 数据的字节顺序(小端或大端)
  • 如果数据类型是子数组, 则其形状和数据类型是什么。
ndarray的值存储在缓冲区中, 可以将其视为内存字节的连续块。因此, 如何解释这些字节由dtype目的。
构造一个数据类型(dtype)对象:数据类型对象是numpy.dtype类的实例, 可以使用以下方法创建numpy.dtype.
参数:obj:要转换为数据类型对象的对象。 align:[bool, 可选]在字段中添加填充以匹配C编译器将为类似的C结构输出的内容。 copy:[bool, 可选]制作数据类型对象的新副本。如果为False, 则结果可能只是对内置数据类型对象的引用。
# Python Program to create a data type objectimport 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 integerimport numpy as np# i4 represents integer of size 4 byte# > represents big-endian byte ordering and# < represents little-endian encoding.# dt is a dtype objectdt = 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: 4Name of data type is: int32

类型说明符(以上情况为i4)可以采用不同的形式:b1, i1, i2, i4, i8, u1, u2, u4, u8, f2, f4, f8, c8, c16, a(表示字节, 整数, 无符号) int, float, 指定字节长度的复数和固定长度字符串(整数)int8, …, uint8, …, float16, float32, float64, complex64, complex128(这次具有位大小)
注意 :dtype与type不同。
# Python program to differentiate# between type and dtype.import numpy as npa = np.array([1])print("type is: ", type(a))print("dtype is: ", a.dtype)

输出如下:
type is:     dtype is:   int32

具有结构化数组的数据类型对象:
数据类型对象对于创建结构化数组很有用。结构化数组是包含不同类型数据的数组。可以借助字段来访问结构化数组。
字段就像为对象指定名称。如果是结构化数组, 则dtype对象也将被结构化。
# Python program for demonstrating # the use of fieldsimport 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 gradesprint(dt['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 npdt = 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']

    推荐阅读