Numpy Tutorial

Author

Amanda Ng

NumPy is an open source Python library designed for fast, efficient numerical computing, especially when working with large datasets or performing mathematical operations. It introduces multidimensional array data structures that enables vectorized operations of which we can apply computations across entire arrays without writing explicit loops, making it faster than standard Python lists for numerical tasks. It also offers a large library of functions for linear algebra, statistics, etc.

0. Introduction to Array

In computer programming, an array is a structure for storing and retrieving data. In an array, each cell stores one element of the data. A 1D array is similar to a list and a 2D array is similar to a table.

Most NumPy arrays have some restrictions:

  • All elements of the array must be of the same type of data
  • Once created, the total size of the array can’t change.
  • The shape must be “rectangular”, not “jagged”; e.g., each row of a two-dimensional array must have the same number of columns.

1. Creating Array

The simplest way to create an array is to use wrap a list with np.array().

The example below creates a 1D array with values 1 to 6.

To create multidimensional array, use nested lists.

The example below creates a 2D array with 3 rows, each row has 2 elements.

As an exercise, create an array that looks like this

23 45 67
123 456 789

Aside from listing the elements explicitly, we can also create array with elements as a range of values, using np.arange().

We can also create an array that stores a range of values with evenly spaced interval in between, using np.linspace().

As an exercise, create an array with 7 evenly spaced elements starting from 12 and ends at 86.

Sometimes, it is also useful to set up an array with all zeros. We can use np.zeros() to do so. Inside the function, set up the array dimension using a tuple (). You can also specify the data type as integer using dtype=int option.

Similarly, we can set up an array with all onces using np.ones(). Inside the function, set up the array dimension using a tuple ().

Aside from 0 and 1, we can create an array of given shape, filled with specificed value using np.full((shape), fill_value).

We can also create an array of given shape, filled with random numbers using np.random.rand(). Do not wrap the shape with a tuple here.

As an exercise, create an array with 5 rows and 6 columns, all filled with 8.

2. Array attributes

Recall we created an array b as follow:

The number of dimensions (i.e. number of columns in 2D array) of an array is contained in the ndim attribute.

The total number of elements in array is contained in the size attribute.

The shape of an array is a tuple of non-negative integers that specify the number of elements along each dimension. In 2D array, we get a tuple indicating number of rows and number of columns.

Arrays usually contain elements of only one “data type”. The data type is recorded in the dtype attribute.

As an exercise, report the number of rows, number of columns and total number of elements in the array exercise_4_array (You can use this variable name directly, it has been preloaded).

3. Array operations

3.1 Check arrays equality

You can check if two arrays are the same using np.array_equal(array_1, array2). For instance

3.2 Arithmetic operations

To conduct element-wise arithmetic operations on arrays such as +, -, *, /, **, we require the arrays to be of the same size.

3.3 Unary operations

Many unary operations, such as computing the sum of all the elements in the array, are implemented as methods of the ndarray class.

Methods include:

  • .mean()
  • .median()
  • .sum()
  • .min()
  • .max()
  • .std()
  • .var()
  • .round()
  • .ceil()
  • .floor()

For example, we can compute the sum of all elements in 1D array a as follow

By default, these operations apply to the array as though it were a list of numbers, regardless of its shape. However, by specifying the axis parameter you can apply an operation along the specified axis of an array.

When axis = 0, we are applying the function on each column. When axis = 1, we are applying the function on each row. Recall that the b array is a 2D array

Here are some examples:

where the first column sum is \(1+ 3 + 5 = 9\) and the second column sum is \(2 + 4+ 6 = 12\).

s an exercise, find out what are the column means for exercise_4_array (You can use this variable name directly, it has been preloaded).

3.4 Universal operations

We can also apply element wise transformation to an array. Some examples include

  • np.exp(array): exponentiate all entries
  • np.sqrt(array): take square root of all entries
  • np.add(array1, array2): element-wise addition

As an exercise, take square root of all entries in exercise_4_array (You can use this variable name directly, it has been preloaded) and store it under exercise_6_array.

4. Transposing and reshaping arrays

To transpose an array, use the .T method. For instance

We can also reshape arrays into a desired shape with method .reshape()

If we want to transform a multidimensional array into a 1D array, i.e. flattening the array, we can use .flatten() or .ravel(). With ravel(), the new array created is a reference to the parent array. So, any changes to the new array will affect the parent array as well. But since ravel does not create a copy, it’s more memory efficient.

The example below demonstrates flatten and ravel applied on b and how they affect the parent array (b) if modifications are done on the new arrays (b_flatten and b_ravel).

As an exercise, flatten in exercise_4_array (You can use this variable name directly, it has been preloaded) and store it under exercise_7_array. When we make edits on exercise_7_array, we do not want the modifications to be reflected on exercise_4_array.

5. Indexing and slicing

We can index and slice arrays the same way as in Python lists.

Recall that in Python, indexing starts from 0. We also index elements by counting backwards and adding a negative sign to the count. To slice a range of elements, use start:stop:step. By default, stop is length of the array and step is 1. Note that stop is exclusive.

Multidimensional arrays can have one index per axis. These indices are given in a tuple separated by commas.

As an exercise, extract the 3rd column entries in all rows in exercise_4_array (You can use this variable name directly, it has been preloaded) and store it under exercise_8_array.

Return to Learning Hub Homepage

Learning Hub Homepage