Introduction

NumPy is an open-source extension for Python that allows us to use vectors and matrices. We can also use it to work in the domain of linear algebra and fourier transforms.

By using this library, we can get faster results than those obtained from the traditional Python lists. This happens due to its locality reference (the data is stored at one continuous place in memory).

In this article we will go through five useful NumPy functions.

  • array
  • transpose
  • reshape
  • sin
  • around

The recommended way to run this notebook is to click the “Run” button at the top of this page, and select “Run on Binder”. This will run the notebook on mybinder.org, a free online service for running Jupyter notebooks.

Let’s begin by importing Numpy and listing out the functions covered in this notebook.

In [ ]:

import numpy as np

In [ ]:

# List of functions explained 
function1 = np.array
function2 = np.transpose
function3 = np.reshape
function4 = np.sin
function5 = np.around

Function 1 – np.array

We use this function when we want to create a NumPy array.

In [ ]:

# Example 1 - working
np.array([5, 8, 4])

Out[ ]:

dtype('int64')

Here, we created a 1-dimension NumPy array. It handles integer data type elements by default.

In [ ]:

# Example 2 - working
np.array([6, 7, 9.0])

Out[ ]:

dtype('float64')

Here, we created a 1-dimension NumPy array. It handles float data type elements by default.

In [ ]:

# Example 3 - breaking (to illustrate when it breaks)
np.array([2, 3, 'five'], dtype=int)
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-27-247950377178> in <module>()
      1 # Example 3 - breaking (to illustrate when it breaks)
----> 2 np.array([2, 3, 'five', True], dtype=int)

ValueError: invalid literal for int() with base 10: 'five'

With dtype attribute, we can set the default data type. If we use this parameter with an incompatible set of elements, we will get this error.

This function is very useful when we want to turn an array-like variable into a NumPy Array in order to apply any of the numerous NumPy functions.

Function 2 – np.transpose

This function returns the transpose of an array. The transpose flips an array over its diagonal; that is, it switches the row and column indices of the array.

In [ ]:

# Example 1 - working
x = np.array([[3, 2, 9], [5, 7, 1]])
np.transpose(x)

Out[ ]:

array([[3, 5],
       [2, 7],
       [9, 1]])

Here, we got the transpose of the 2 x 3 original array, which is a 3 x 2 array.

In [ ]:

# Example 2 - working
x = np.array([[[3, 2], [5, 7], [4, 6]]])
print('shape from original vector: {}'.format(x.shape))

x = np.transpose(x, (1, 2, 0)).shape
print('shape from transposed vector: {}'.format(x))
shape from original vector: (1, 3, 2)
shape from transposed vector: (3, 2, 1)

By using the second argument (axes), you can permute the axes by a given order.

In [ ]:

# Example 3 - breaking (to illustrate when it breaks)
x = np.array([[[3, 2], [5, 7], [4, 6]]])
print('shape from original vector: {}'.format(x.shape))

x = np.transpose(x, (1, 2, 0, 3)).shape
print('shape from transposed vector: {}'.format(x))
shape from original vector: (1, 3, 2)
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-80-a29ce43c8b93> in <module>()
      3 print('shape from original vector: {}'.format(x.shape))
      4 
----> 5 x = np.transpose(x, (1, 2, 0, 3)).shape
      6 print('shape from transposed vector: {}'.format(x))

<__array_function__ internals> in transpose(*args, **kwargs)

/usr/local/lib/python3.6/dist-packages/numpy/core/fromnumeric.py in transpose(a, axes)
    649 
    650     """
--> 651     return _wrapfunc(a, 'transpose', axes)
    652 
    653 

/usr/local/lib/python3.6/dist-packages/numpy/core/fromnumeric.py in _wrapfunc(obj, method, *args, **kwds)
     59 
     60     try:
---> 61         return bound(*args, **kwds)
     62     except TypeError:
     63         # A TypeError occurs if the object does have such a method in its

ValueError: axes don't match array

When you use the second argument, you have to be sure to use the right number of axes, otherwise, it will crash.

You can use this function when you want to get the transpose from an array (e.g. when you work with linear regression).

Function 3 – np.reshape

This function is useful when you want to change the shape of an array without changing its content.

In [ ]:

# Example 1 - working
a = np.array([[1,2,3], [4,5,6]])
np.reshape(a, 6)

Out[ ]:

array([1, 2, 3, 4, 5, 6])

Here, we reshaped the array to a 1-dimension array of length 6.

In [ ]:

# Example 2 - working
a = np.array([[1,2,3], [4,5,6]])
np.reshape(a, 6, order='F')

Out[ ]:

array([1, 4, 2, 5, 3, 6])

By using the parameter ‘order’, we can place the elements into the reshaped array using this index order. ‘F’ means to read / write the elements using Fortran-like index order, with the first index changing fastest, and the last index changing slowest.

In [ ]:

# Example 3 - breaking (to illustrate when it breaks)
a = np.array([[1,2,3], [4,5,6]])
np.reshape(a, 6, order='G')
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
/usr/local/lib/python3.6/dist-packages/numpy/core/fromnumeric.py in _wrapfunc(obj, method, *args, **kwds)
     60     try:
---> 61         return bound(*args, **kwds)
     62     except TypeError:

TypeError: order not understood

During handling of the above exception, another exception occurred:

TypeError                                 Traceback (most recent call last)
<ipython-input-86-75032211811f> in <module>()
      1 # Example 3 - breaking (to illustrate when it breaks)
      2 a = np.array([[1,2,3], [4,5,6]])
----> 3 np.reshape(a, 6, order='G')

<__array_function__ internals> in reshape(*args, **kwargs)

/usr/local/lib/python3.6/dist-packages/numpy/core/fromnumeric.py in reshape(a, newshape, order)
    299            [5, 6]])
    300     """
--> 301     return _wrapfunc(a, 'reshape', newshape, order=order)
    302 
    303 

/usr/local/lib/python3.6/dist-packages/numpy/core/fromnumeric.py in _wrapfunc(obj, method, *args, **kwds)
     68         # Call _wrapit from within the except clause to ensure a potential
     69         # exception has a traceback chain.
---> 70         return _wrapit(obj, method, *args, **kwds)
     71 
     72 

/usr/local/lib/python3.6/dist-packages/numpy/core/fromnumeric.py in _wrapit(obj, method, *args, **kwds)
     45     except AttributeError:
     46         wrap = None
---> 47     result = getattr(asarray(obj), method)(*args, **kwds)
     48     if wrap:
     49         if not isinstance(result, mu.ndarray):

TypeError: order not understood

When you use the order parameter, make sure to set a valid argument (‘C’, ‘F’ or ‘A’).

In this case, we used an invalid value ‘G’, that’s why it crashed.

You can use this function when you want to reshape an array to make it compatible with other arrays for arithmetic operations.

Function 4 – np.sin

This function implements the trigonometric sine

In [ ]:

# Example 1 - working
np.sin(np.pi/2.)

Out[ ]:

1.0

Here, we printed sine of one angle.

In [ ]:

# Example 2 - working
np.sin(np.array((0., 30., 45., 60., 90.)) * np.pi / 180. )

Out[ ]:

array([0.        , 0.5       , 0.70710678, 0.8660254 , 1.        ])

Here, we printed sines of an array of angles given in degrees

In [ ]:

# Example 3 - breaking (to illustrate when it breaks)
np.sin('5')
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-99-c44e3e8155a6> in <module>()
      1 # Example 3 - breaking (to illustrate when it breaks)
----> 2 np.sin('5')

TypeError: ufunc 'sin' not supported for the input types, and the inputs could not be safely coerced to any supported types according to the casting rule ''safe''

In this case, we are getting an error due to the data type of the argument. Always use numeric values.

The sine is one of the fundamental functions of trigonometry, so you might need to use this function often.

Function 5 – np.around

With this function, you can evenly round to the given number of decimals.

In [ ]:

# Example 1 - working
np.around([0.37, 1.64])

Out[ ]:

array([0., 2.])

By default, it rounds to 0 decimals.

In [ ]:

# Example 2 - working
np.around([0.37, 1.64], decimals=1)

Out[ ]:

array([0.4, 1.6])

Here, we round the values to 1 decimal.

In [ ]:

# Example 3 - breaking (to illustrate when it breaks)
np.around([0.37, '1.64'])
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-105-43ffcc5bec25> in <module>()
      1 # Example 3 - breaking (to illustrate when it breaks)
----> 2 np.around([0.37, '1.64'])

<__array_function__ internals> in around(*args, **kwargs)

/usr/local/lib/python3.6/dist-packages/numpy/core/fromnumeric.py in around(a, decimals, out)
   3222 
   3223     """
-> 3224     return _wrapfunc(a, 'round', decimals=decimals, out=out)
   3225 
   3226 

/usr/local/lib/python3.6/dist-packages/numpy/core/fromnumeric.py in _wrapfunc(obj, method, *args, **kwds)
     56     bound = getattr(obj, method, None)
     57     if bound is None:
---> 58         return _wrapit(obj, method, *args, **kwds)
     59 
     60     try:

/usr/local/lib/python3.6/dist-packages/numpy/core/fromnumeric.py in _wrapit(obj, method, *args, **kwds)
     45     except AttributeError:
     46         wrap = None
---> 47     result = getattr(asarray(obj), method)(*args, **kwds)
     48     if wrap:
     49         if not isinstance(result, mu.ndarray):

TypeError: ufunc 'rint' not supported for the input types, and the inputs could not be safely coerced to any supported types according to the casting rule ''safe''

Always make sure to use numbers instead of strings, otherwise it will crash.

This function is useful when we are using a huge amount of data and we want to simplify it by reducing the number of decimals.

Conclusion

As you can see from this brief article, NumPy has many features that helps you to handle arrays. There are many more functionalities that you can review from the NumPy official documentation.