. Advertisement .
..3..
. Advertisement .
..4..
Without a shade of doubt, Python doesn’t come with in-built support for an array. Thus, you need to use a commonly employed Python library for array and matrix computations.
A Numpy array is the most versatile Python data structures, which creates most Python-based machine learning and data science applications.
It offers users a wide range of functions and available classes for performing various operations on matrices. This tutorial will guide you the best methods to convert a matrix to a Numpy array.
How To Convert A Matrix To A Numpy Array
Method 1: Use The numpy.flatten() Function
This option takes n-dimensional arrays and converts them to single-dimensional ones. Yet, bear in mind that it works with nparray objects only. Here is it converts a matrix to array:
import numpy as np
example_arr = np.array([[11,22,33,44],[55,66,77,88]])
print(example_arr.flatten())
Output:
[11 22 33 44 55 66 77 88]
It is worth noting that a matrix type object will need to be used with the asarray(). After converting this object into an array, use the flatten()
to finish the overall task.
import numpy as np
exp_arr = np.matrix([[12,19,29,28],[22,15,18,13]])
new_array = (np.asarray(exp_arr)).flatten()
print(new_array)
Output:
[12 19 29 28 22 15 18 13]
Method 2: Use The numpy.ravel() Function
The ravel()
and flatten()
functions appear to work in the same way, despite some slight yet unnoticeable differences. Both can convert n-dimensional arrays to single dimension ones.
The main difference is that the ravel()
library function can also deal with such objects as a list of arrays. To be specific, the flatten()
returns the original’s copy while the other gives an overview of the original. Here is how it converts a matrix:
import numpy as np
exp_arr2 = np.array([[86,56,71],[65,29,33]])
print(exp_arr2.ravel())
Output:
[86 56 71 65 29 33]
Method 3: Use The numpy.reshape() Function
The array’s overall shape can be modified, yet its contents will not be altered thanks to the help of the reshape()
function.
import numpy as np
exp_arr3 = np.array([[7,4,5,52],[2,5,64,14]])
print(exp_arr3.reshape(-1))
Output:
[ 7 4 5 52 2 5 64 14]
How To Sort Arrays In Numpy
After converting matrices to Numpy arrays, you can also sort this list with the inbuilt sort function. Numerical or alphabetical array elements will be both dealt with by this one.
The function tends to sort in ascending order by default. With a multidimensional array, it will work in the innermost one.
Code:
import numpy as np
sort_arr = np.array([[28,22,15,18],[19,29,88,89]])
print(np.sort(sort_arr))
[[15 18 22 28]
[19 29 88 89]]
Conclusion
The article has provided users with three simple yet effective methods to convert a matrix to a Numpy array. Check the article again to choose a suitable way for your situation.
Leave a comment