How to change array (or matrix) type with numpy in python ?

Published: July 22, 2020

Tags: Python; Numpy;

DMCA.com Protection Status

Examples of how to change array (or matrix) type with numpy in python

Change the type of an existing matrix

Let's consider the following matrix of integer type:

import numpy as np

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

print(A)
print(A.dtype)

donne ici

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

et

int64

To change the type, a solution is to use astype (see numpy.ndarray.dtype)

A = A.astype('float64')

print(A)
print(A.dtype)

returns

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

and

float64

Initialization of a matrix with a given type

It is also possible to specify the type of a matrix during the creation:

import numpy as np

A = np.array([[1, 2, 3]], dtype=float)

print(A)

print(A.dtype)

returns

[[1. 2. 3.]]

and

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