Learning Objectives

  • Understand when and where you should use numpy.
  • Be able to create several data types that numpy supports.
  • Be able to use mathematical operators (or functions) with numpy.

Contents

  1. References
  2. Introduction
  3. Getting Started
  4. Data Types
  5. Arithmetic
  6. Conclusion

References

If you are familiar with MATLAB, you might be able to get started quicker by looking at the similarities and differences between the two: NumPy for MATLAB users — NumPy v1.20 Manual.


Introduction

Numpy is a large library designed to perform fast mathematical calculations. It also implements new data types to more closely resemble the engineering and sciences disciplines. Numpy is used for many other libraries that we will be using in this course, including matplotlib and pandas.

The core of numpy is a multidimensional list (aka array). This can be visualized as something like a matrix. However, numpy allows us to specify the dimensions, so we can make a 1D, 2D, 3D, or nD array using numpy. This holds our data. Then numpy comes equipped with several methods that allows us to perform calculations on these arrays, such as multiplication, exponent, division, transformations, and so forth.


Getting Started

Numpy is imported through a module called numpy. In most cases, we abbreviate numpy as np.

>>> import numpy as np
>>> a = np.array([[1, 2, 3, 4, 5], [-1, -2, -3, -4, -5]])
>>> print(a)
array([[ 1,  2,  3,  4,  5],
       [-1, -2, -3, -4, -5]])
>>> a.ndim
2
>>> a.shape
(2, 5)
>>> a.size
10

We create a new array by using np.array. We have to specify a single list, but notice that I have lists inside of the outer list. This gives us two dimensions. Inside of each dimension is 5 values. This is why a.shape returns (2, 5). This tells us we have 2 rows, and in each row, we have 5 columns.


Data Types

Some of the speed and efficiency of numpy comes from the fact that it knows where to send things in the computer to be the most efficient. The computer can calculate integer arithmetic much much faster than it can calculate float (decimal) data types. Knowing this, numpy allows us to also specify the memory footprint–that is, how many 0s and 1s is our data going to require?

>>> import numpy as np
>>> a = np.array([[1, 2, 3, 4, 5], [-1, -2, -3, -4, -5]], dtype=np.int16)
>>> print(a)
array([[0, 0, 0, 0, 0],
       [0, 0, 0, 0, 0]], dtype=int16)

You can see that we can specify the data type of the values in our array by using dtype. The np.int16 means a 16-bit integer. A bit is one 0 or 1, also known as a base 2 digit. So, 16 bits will give us \(\pm~2^{16-1}\). In a computer np.int16 means a signed integer, meaning that it can be positive or negative. Since computers only store zeroes and ones, we set the upper bit to 1 if the value is negative or upper bit to 0 if the value is positive. This is why we only have \(16-1\) or 15 bits to actually store the magnitude of the number.

Since we lose a bit to gain the ability to store negative numbers, we can turn this off if we know our data will only be positive. These are called unsigned data types and are prefixed with a u. For example, np.uint16 will store values from 0 to \(2^{16}-1\), which is around 0 to 65,536.

The table below describes some of the data types numpy supports.

Data TypeSize (in bits)Data That Can Be Stored
np.int88\(\pm~2^{8-1}-1=\pm~128\)
np.int1616\(\pm~2^{16-1}-1=\pm~32,767\)
np.int3232\(\pm~2^{32-1}-1=\pm~2,147,483,647\)
np.int6464\(\pm~2^{64-1}-1=\pm~9,223,372,036,854,775,807\)
np.uint88\(\pm~2^{8}-1=255\)
np.uint1616\(\pm~2^{16}-1=65,535\)
np.uint3232\(\pm~2^{32}-1=4,294,967,295\)
np.uint6464\(\pm~2^{64}-1=18,446,744,073,709,551,615\)
np.float3232Stores decimal point. Fractional portion is 23 bits.
np.float6464Stores decimal point. Fractional portion is 52 bits.
np.complex64/64Stores a real and imaginary portion of a complex number.
Some data types in numpy. For a more comprehensive list see: Data types — NumPy v1.20 Manual

The integer data types are the quickest for arithmetic, and we can double their capacity if we can lose the ability to store negative numbers. If we need a decimal point, we have to use np.float32 or np.float64. np.float32 is smaller and on some computers faster than np.float64.

We can double check the information given by these data types by using np.iinfo() for integers and np.finfo() for floating point.

>>> import numpy as np
>>> np.iinfo(np.int16)
iinfo(min=-32768, max=32767, dtype=int16)
>>> np.iinfo(np.uint8)
iinfo(min=0, max=255, dtype=uint8)
>>> np.finfo(np.complex)
finfo(resolution=1e-15, min=-1.7976931348623157e+308, max=1.7976931348623157e+308, dtype=float64)
>>> np.finfo(np.float32)
finfo(resolution=1e-06, min=-3.4028235e+38, max=3.4028235e+38, dtype=float32)
>>> np.finfo(np.float64)
finfo(resolution=1e-15, min=-1.7976931348623157e+308, max=1.7976931348623157e+308, dtype=float64)

Arithmetic

Now that we know how the data is stored, let’s see what we can do with them. We can use many of the same operators we used with integers and float, such as +, -, /, and so forth.

>>> import numpy as np
>>> a = np.array([1, 2, 3, 4, 5])
>>> b = -a   # Negation
>>> b
array([-1, -2, -3, -4, -5])
>>> a * b    # Elementwise Multiplication
[ -1  -4  -9 -16 -25]
>>> a ** 3   # Power
[  1   8  27  64 125]
>>> -5 * np.sin(a * (np.pi / 2))  # Trig
array([-5.0000000e+00, -6.1232340e-16,  5.0000000e+00,  1.2246468e-15,
       -5.0000000e+00])
>>> a < 3     # Boolean conditionals
array([ True,  True, False, False, False])

We can also do vectored operations.

>>> import numpy as np
>>> a = np.array( [[1.0, 0.0, 0.0],
                   [0.0, 1.0, 0.0],
                   [0.0, 0.0, 1.0]] )  # Identity matrix
>>> b = np.array( [[1.0, 0.0, -1.0],
                   [0.0, 1.0, 2.75],
                   [0.0, 0.0, 1.0]] )  # Translation matrix
>>> c = np.array( [10.0,
                   25.1,
                   31.2] )  # 1x3 Vector
>>> d = np.array ( [-1.5,
                    2.5,
                    1.0] )   # Another 1x3 Vector
>>> a @ c         # Identity Matrix multiplication
[10.  25.1 31.2]
>>> b @ c         # Translation Matrix multiplication
[-21.2 110.9   0. ]
>>> np.dot(c, d)  # Dot product
78.95
>>> np.cross(a, b) # Cross product
[[-0.    1.    0.  ]
 [ 2.75  0.    0.  ]
 [ 0.    0.    0.  ]]

Conclusion

Numpy is an enormous library, and it even contains several submodules for specific industries (see below)

It is not possible that I cover all of the features of numpy, especially since many of you are industrial engineers, or mechanical engineers, or nuclear engineers, or environmental engineers, or chemical engineers, or bio engineers, etc, etc, etc. There are so many different disciplines that use numpy for a variety of reasons.

The purpose of this lecture is to get you into the documents so that when you finish this course, you know where to look for information.