NumPy Data Types
NumPy Data Types
By default python provide 5 main data types strings, integer, float, boolean and complex.
- strings used to represent text data eg.:'test string'.
- integer used to represent integer data eg.:1,2,3,4,-1.
- float used to represent real numbers eg.:1.0,1.2,3.3.
- boolean used to represent true or false.
- complex used to represent complex number eg.:1.0 + 2.0j,2.5 + 1.5j.
In the case of NumPy 11 main data types are there. They are integer, boolean, unsigned integer, float, complex float, timedelta, datetime, object, string, unicode string and void. It is represented as,
- i : integer
- b : boolean
- u : unsigned integer
- f : float
- c : complex float
- m : timedelta
- M : datetime
- O : object
- S : string
- U : unicode string
- V : void or fixed chunk of memory for other type
Find the data type of NumPy array
import numpy as np
arr = np.array([1, 2, 3, 4])
print(arr.dtype)From the above example we can find the print command with in that arr.dtype is used for finding the data type of array element.
Create Array with defined data type / Changing data type of array
import numpy as np
arr = np.array([1, 2, 3, 4], dtype='S')
print(arr)
print(arr.dtype)From the above code it will return
[b'1' b'2' b'3' b'4']
|S1Here the integer in converted to string type. The prefix b indicates that the literal should become a bytes literal. The 1 after the S is known as size of the item. Here 1 byte is the size of the data. and if we add two digit number to the array then the type will be S2 because the size of the data is 2 byte. Also this size can be passed to the dtype itself, like S2. For i, u, f, s and U we can define the size. Also we can't convert the string data to integer like if we passed string a to and integer array and define the type to i then it will be throw the error.