WHAT IS THE DATA TYPE OF ARRAY IN PYTHON NUMPY?

Python NumPy Data Types

Numpy data types and the characters used to represent them are listed below-

i – integer
b – boolean
u – unsigned integer
f – float
c – complex float
m – timedelta
M – datetime
O – object
S – string
U – unicode string
V – fixed chunk of memory for other type ( void )

How to check the data type of an Array?

We can check the data type of NumPy array object by using its property named dtype as shown in below example-

import numpy as np

arr1 = np.array([1, 2, 3])


arr2 = np.array(['apple', 'banana', 'mango'])

print(arr1.dtype)
print(arr2.dtype)

Output-

int64
<U6

How to create arrays with a defined data type?

We can define the data type of array at the time of its creation by passing argument dtype in the array(), as shown in following example.

import numpy as np

arr1 = np.array([1, 2, 3], dtype='S')

arr2 = np.array([4, 5, 6], dtype='i4') #i4-size of datatype is defined
print(arr1)
print(arr1.dtype)
print(arr2)
print(arr2.dtype)

Output-

[b'1' b'2' b'3']
|S1
[4 5 6]
int32

Explanation-

dtype=’S’ – it will create an array of string datatype.

dtype=’i4′ – it will create an array of 4bytes integer datatype, as size is also defined there.

What if a Data Type Value Can’t Be Converted?

NumPy will raise a ValueError when an array can’t be casted in given datatype. As shown in following example, a non integer string like ‘a’ can’t be converted to integer.

import numpy as np

arr = np.array(['a', '1', '2'], dtype='i')

How to convert the data type of an existing array?

We can convert the data type of existing arrays by using astype() method and specifying datatype character in it as parameter. The astype() method creates a copy of the array, and allows us to specify the data type as a parameter.

import numpy as np

arr = np.array([1.1, 2.2, 3.3])

newarr = arr.astype('i')

print(newarr)
print(newarr.dtype)

Output-

[1 2 3]
int32

Posted

in

Tags:

Comments

Leave a Reply