How to Convert NumPy Matrix to Array (With Examples)


You can use the following methods to convert a NumPy matrix to an array:

Method 1: Use A1

my_array = my_matrix.A1

Method 2: Use ravel()

my_array = np.asarray(my_matrix).ravel()

Both methods return the same result, but the second method simply requires more typing.

The following examples show how to use each method in practice.

Example 1: Convert NumPy Matrix to Array Using A1

The following code shows how to use the A1 property to convert a NumPy matrix to an array:

import numpy as np

#create NumPy matrix with 3 columns and 5 rows
my_matrix = np.matrix(np.arange(15).reshape((5, 3)))

#view NumPy matrix
print(my_matrix)

[[ 0  1  2]
 [ 3  4  5]
 [ 6  7  8]
 [ 9 10 11]
 [12 13 14]]

#convert matrix to array
my_array = my_matrix.A1

#view NumPy array
print(my_array)

[ 0  1  2  3  4  5  6  7  8  9 10 11 12 13 14]

We can see that the NumPy matrix has been converted to an array with 15 values.

We can confirm that it is NumPy array by using the type() function:

#check type of my_array
type(my_array)

numpy.ndarray

It is indeed a NumPy array.

Example 2: Convert NumPy Matrix to Array Using ravel()

The following code shows how to use the ravel() function to convert a NumPy matrix to an array:

import numpy as np

#create NumPy matrix with 3 columns and 5 rows
my_matrix = np.matrix(np.arange(15).reshape((5, 3)))

#view NumPy matrix
print(my_matrix)

[[ 0  1  2]
 [ 3  4  5]
 [ 6  7  8]
 [ 9 10 11]
 [12 13 14]]

#convert matrix to array
my_array = np.asarray(my_matrix).ravel()

#view NumPy array
print(my_array)

[ 0  1  2  3  4  5  6  7  8  9 10 11 12 13 14]

We can see that the NumPy matrix has been converted to an array with 15 values.

We can confirm that it is NumPy array by using the type() function:

#check type of my_array
type(my_array)

numpy.ndarray

It is indeed a NumPy array.

Additional Resources

The following tutorials explain how to perform other common tasks in NumPy:

How to Fill NumPy Array with Values
How to Remove Specific Elements from NumPy Array
How to Replace Elements in NumPy Array
How to Get Specific Row from NumPy Array

Leave a Reply

Your email address will not be published.