3 Basic Commands to Manipulate NumPy 2d-arrays

NumPy or Numerical Python is one of the packages in Python for all things computing with numerical values. Learning NumPy makes one’s life much easier to compute with multi-dimensional arrays and matrices. A huge collection of very useful mathematical functions available to operate on these arrays these arrays makes it one of the powerful environment for scientific computing in Python. In an earlier post,

we saw how we can get started using NumPy’s 1d-arrays with some basic operations on it. Here, we are will going over the 3 most basic and useful commands to learn NumPy 2d-array.

Load NumPy Package

Let us load the numpy package with the shorthand np.

>import mumpy as np

How to create 2d-array with NumPy?

Let us create 2d-array with NumPy, such that it has 2-rows and three columns. We can simply use two tuples of size 3 with np.array function as

# create a 2d-array of shape 2 x 3
>b = np.array([(1.5,7,8), (41,45,46)])
# print the 2d-array 
>print(b)
[[  1.5   7.    8. ]
 [ 41.   45.   46. ]]

How to transpose NumPy array?

We can use transpose() function to transpose a 2d-array in NumPy.

# transpose the array
# note the shape is 3 x 2 np.transpose(b) 
>i = np.transpose(b)
array([[  1.5,  41. ],
       [  7. ,  45. ],
       [  8. ,  46. ]])

How to flatten a nd-array to 1d-array?

We can use ravel() function in NumPy to flatten 2d-array into 1d-array.

>b.ravel()
array([  1.5,   7. ,   8. ,  41. ,  45. ,  46. ])

How to re-shape NumPy array?

We can use reshape() function to change the shape of 2d-array.

>b.reshape(3,2)
array([[  1.5,   7. ],
       [  8. ,  41. ],
       [ 45. ,  46. ]])