In this tutorial you will learn:
Data Types in NumPy
NumPy provides a greater flexibility to the users by providing them a great number of in built data types, which could be declared and further used by the programmers as per the requirement of the overall program sequence, hence avoiding any memory loss, increasing space efficiency and overall improving the program’s speed. A character code uniquely identifies the NumPy built in data type.
Character Codes for Built in Data Types
Declaring and Using NumPy Data Types
We can declare an array of any of the above mentioned data types and further use in our code. For a specific data type we declare it by assigning character code parameter ‘dtype’ as demonstrated in follow up examples. Below are the given examples for declaration of all types
In this example we are creating an array of data type Boolean.
print ('**NumPy Data Types**') arr = np.array((False,True),dtype='b') print('Content of Boolean Array are :', arr) print('Type of Array is:' , arr.dtype)
In this example we are creating an array of data type Int having 8 bytes
import numpy as np arr = np.array([20,30,40,50,60,70], dtype='i8') print('Content of Int Array are :', arr) print('Type of Array is:' , arr.dtype)
In this example we are creating an array of data type unsigned int having 16 bytes
import numpy as np arr = np.array([13,14,15,12], dtype='uint16') print('Content of Unsigned Int Datatype Array are :', arr) print('Type of Array is:' , arr.dtype)
In this example we are creating an array of data type float having 64 bytes
import numpy as np arr = np.array([13.223,17.921,66.96,69.11,80], dtype='float64') print('Content of float Datatype Array are :', arr) print('Type of Array is:' , arr.dtype)
In this example we are creating an array of data type Complex having 64 bits
import numpy as np arr = np.array([2j, 1+2j, 3-5j,1],dtype='complex64') print('Content of Complex Datatype Array are :',arr) print('Type of Array is:' , arr.dtype)
In this example we will create a datetime object
from datetime import date today = date.today(); print('Time now is',today)
In this example we will create an a python object
import numpy as np arr = np.array([9,8,7,6,5,4], dtype='O') print('Content of Object Datatype Array are :',arr) print('Type of Array is:' , arr.dtype)
In this example we will create a String datatype array.
import numpy as np arr = np.array([10,20,30,40,50,60], dtype='S') print('Content of String Datatype Array are :',arr) print('Type of Array is:' , arr.dtype)
In this example we will create a unicode array
import numpy as np arr = np.array([10, 20, 9,1],dtype='U') print('Content of Unicode Datatype Array are :',arr) print('Type of Array is:' , arr.dtype)
In this example we will create a Raw Data array
import numpy as np arr = np.array(bytes('Sourcecodester', "utf8"), dtype='V') print('Content of Raw Datatype Array are :',arr) print('Type of Array is:' , arr.dtype)