How to get the type of an array (or matrix) with numpy in python ?


Examples of how to get the type of a matrix using numpy in python:

Get the type of a matrix using the attribute dtype

To get the type a matrix, a solution is to use dtype, example:

import numpy as np

A = np.array([[1.2, 2.3, 3.4]])

print(A.dtype)

returns

float64

Change the type of a matrix

To indicate the type of a matrix, a solution is to do:

A = np.array([[1.2, 2.3, 3.4]], dtype=int)

print(A)

print(A.dtype)

returns respectively

[[1 2 3]]

and

int64

Or to use astype to change the type of an existing matrix::

A = A.astype('float64')

print(A.dtype)

returns

float64

Combine matrix with different type

It is important to check the type of a matrix to avoid loosing information, an example let's consider the following matrix A:

A = np.array([[10, 20, 30], [60, 20, 10], [50, 30, 90]])

returns

[[10 20 30]
 [60 20 10]
 [50 30 90]]

and the matrix B:

B= np.array([[2.1, 7.3, 4.5]])

returns

[[2.1 7.3 4.5]]

Now, if the matrix A is updated using B, like:

A[1,:] = B

returns

[[10 20 30]
 [ 2  7  4]
 [50 30 90]]

but the elements of B have been modified. To avoid that a solution would have been to do first:

A = A.astype('float64')

A[1,:] = B

returns

[[10.  20.  30. ]
 [ 2.1  7.3  4.5]
 [50.  30.  90. ]]

References