Data Type objects in NumPy Python

Data Type Objects describe the interpretation of the bytes in the fixed-size block corresponding to an array. These objects are instances of Python’s numpy.dtype classIt mainly focuses on :

  • Data Type (int, float, python object, etc.)
  • Data size (number of bytes)
  • The byte order of the data ()
  • If data is sub-array, then the shape and datatype of it.

Remember that the data type objects and scalar types are not the same. Although scalar types can be used when there is a requirement of data type specification in NumPy.

1. Construct a data type object:

Data type object is an instance and can be constructed using NumPy library of Python. Syntax of data type object:

numpy.dtype(object, align, copy)

Significance of the parameter are:

  • Object is the object to convert as the data-type object.
  • Align (boolean): adds padding to the fields to make them comparative to C-struct if align is True.
  • Copy (boolean): creates a new copy of a data type object if True. Otherwise, the output returns a built-in data type object reference on having a False value for the copy field.

In the example below, dtype function gives the data type of the object passed to it.

# Demonstration
import numpy as np 
# to convert np.int32 into a dtype object.
data_type = (np.dtype(np.int32)) 
# Program to construct a data type object
import numpy as np 

# integer of size 8 bit represented as i8.
data_type = np.dtype('i8')
# Byte order of data type
# size of data type
#data type

The functions byteorder and itemsize give the byte order and size of the data type respectively. In the above example, the type specifier is ‘i8’ that is equivalent to int64. Type specifiers can be of different forms such as:

b1 : byte
i1, i2, i4, i8, etc : ints
u1, u2, u4, u8, etc : unsigned ints
f1, f2, f4, f8, etc : floats
c8, c16 : complex

for example: i1 is int8, i2 is int16 and i4 is int 32, etc.

2. Create a structured array using data type object:

data-type object is used for creating a structured array. The structured array is also known as “Record Array”. This provides the ability to have each column with different data types.

# Program to create a structured array using data type object
import numpy as np

employee = np.dtype([('name','S20'), ('age', 'i1'), ('salary', '>i4')])
[('name', 'S20'), ('age', 'i1'), ('salary', '>i4')]
# Program to create a structured array using data type object
import numpy as np 

employee = np.dtype([('name','S20'), ('age', 'i1'), ('salary', '>i4')]) 
# struc_array is a structure array
struc_array = np.array([('Jim', 32, 1200000),('Jam', 39, 2000000)], dtype = employee) 
[(b'Jim', 32, 1200000) (b'Jam', 39, 2000000)]
(b'Jam', 39, 2000000)

Leave a Reply

Your email address will not be published. Required fields are marked *