numpy.dtype() in Python


In Python, each of ndarray has a data type object associated with it. The data type object contains the following data:

  1. Type of data  – int, float, objects, etc.
  2. Data size – Total number of bytes
  3. Data byte order – little-endian or big-endian
  4. Subarray Type – If the data type is subarray its shape and data type
  5. Structured Type – the data type of each field, name of the field, etc.

Basic Syntax

Following is the basic syntax for numpy.dtype() function in Python:

numpy.dtype(object, align, copy)

And the parameters are:

Parameter Description
Object Input object of which dtype should be returned
align Optional bool. It adds padding to fields if set as true.
copy Optional bool. Creates copy of dtype object and returns built in dtype object reference.

Return Value

numpy.dtype() function returns dtype object.

Example

Following are the examples for numpy.dtype() function

Example 1

# Python program for demonstration of numpy.dtype() function
import numpy as np 

# np.int64 will be converted to dtype object. 
print(np.dtype(np.int64)) 

The output for the above program is as given below:

int 64

Example 2

# Python Program to create a data type object 
import numpy as np 

# i2 represents 2 byte sized integer 
# < represents little-endian byte ordering and > represents big-endian encoding. 
dt_object = np.dtype('>i2') 

print("Data Type:",dt_object.name)
print("Size:",dt_object.itemsize)  
print("Byte Order:",dt_object.byteorder) 

The output for the above program is as given below:

Data Type: int16
Size: 2
Byte Order: >

Example 3

# Python Program to create a data type object  
import numpy as np 

# marks with type int16 
dt_object = np.dtype([('marks',np.int16)]) 
print dt_object 

The output for the above program is as given below:

int16

Example 4

# Python Program to create a data type object  
import numpy as np 

# marks with type int16 
dt_object = np.dtype([('marks',np.int16)]) 
arr = np.array([(50,),(60,),(70,)], dtype = dt_object)
print arr 

The output for the above program is as given below:

[(50,) (60,) (70,)]

Example 5

# Python Program to create a data type object  
import numpy as np 

# marks with type int16 
dt_object = np.dtype([('marks',np.int16)]) 
arr = np.array([(50,),(60,),(70,)], dtype = dt_object)
print arr['marks']

The output for the above program is as given below:

[50 60 70]

Example 6

# Python Program to create a data type object 
import numpy as np 

# i8 represents 64 byte sized integer 
# < represents little-endian byte ordering and > represents big-endian encoding. 
dt_object = np.dtype('>i8') 

print("Data Type:",dt_object.name)
print("Size:",dt_object.itemsize)  
print("Byte Order:",dt_object.byteorder) 

The output for the above program is as given below:

Data Type: int64
Size: 8
Byte Order: >