NumPy

Unit 3

More on NumPy

What does ipython tell us about numpy?
  • np?
  • np. + [TAB]
  • np.linspace() + [Shift+TAB]
A numpy cheet sheat

Creating Arrays:

  • numpy.array(): Create an array from a list or iterable.
  • numpy.zeros(): Create an array filled with zeros.
  • numpy.ones(): Create an array filled with ones.
  • numpy.empty(): Create an empty array (uninitialized values).
  • numpy.full(): Create an array filled with a scalar of your choice.
  • numpy.arange(): Create an array with regularly spaced values.
  • numpy.linspace(): Create an array with a specified number of evenly spaced values.

Mathematical Operations:

  • numpy.sqrt(): Compute the square root of each element.
  • numpy.sin(), numpy.cos(), numpy.tan(): Trigonometric functions.
  • numpy.dot(): Dot product of two arrays (matrix multiplication).
  • numpy.cross(): Cross product of two arrays
  • numpy.transpose(): Transpose an array or matrix.

Statistical Functions:

  • numpy.sum(): Sum of array elements.
  • numpy.mean(), numpy.median(): Mean and median of array elements.
  • numpy.std(): Standard deviation of array elements.
  • numpy.max(), numpy.min(): Maximum and minimum values.
  • numpy.argmax(), numpy.argmin(): Indices of maximum and minimum values.

Array Attributes:

  • shape: Get the shape (dimensions) of an array.
  • dtype: Get the data type of an array.
  • ndim: Get the number of dimensions.
  • size: Get the number of elements in an array.

Array Manipulation:

  • numpy.concatenate(): Join arrays along an existing axis.
  • numpy.stack, numpy.vstack(), numpy.hstack(): Stack arrays along new axis, vertically, or horizontally.
  • numpy.split(): Split an array into multiple sub-arrays.
  • numpy.copy(): Create a copy of an array.
  • numpy.resize(): Resize an array.
  • numpy.reshape(): Reshape an array into a new shape.
  • numpy.array_equal(): Check whether two arrays have the same shape and values.

Random Number Generation:

  • numpy.random.randint(): Generate random integers.
  • numpy.random.normal(): Generate random numbers from a normal distribution.
  • numpy.random.seed(): Set the random seed for reproducibility.

Linear Algebra:

  • numpy.linalg.inv(): Compute the matrix inverse.
  • numpy.linalg.det(): Compute the determinant of a matrix.
  • numpy.linalg.eig(): Compute eigenvalues and eigenvectors of a matrix.
#03-02: More advanced numpy modifications

You are given a list of numbers, list1, containing 9 elements. Your task is to perform the following operations using NumPy:

  1. Create a numpy array arr1 from list1.
  2. Create another numpy array arr2 that counts down from 9 to 1.
  3. Reshape arr1 into a 3x3 matrix.
  4. Reshape arr2 into a 3x3 matrix.
  5. Perform element-wise addition between arr1 and arr2 and store the result in a new array called result.
  6. Perform element-wise multiplication between arr1 and arr2 and store the result in a new array called product.
  7. Combine arr1 and arr2 to create a new 6x3 matrix. First use the function concatenate and name the matrix stacked_array_cat, then do the same with one of the stack family of functions and name the array stacked_array_stack.
  8. Check whether the two arrays have the same shape and equal values.
  9. Conceptually go back to step 2, and create arr2 by reversing arr1.
  10. What happens to arr2 if you now change the first element of arr1? Why?

In the following you will find a code block template for the exercise. Store it in $SCIPRO/03_workshop/numpy_exercise.py and fill in the code to complete each step as described.

# This script is intended for interactive exercise.
# Create a python console for the file and walk through the tasks.
# Print your results and check whether they meet your expectations!

import numpy as np

# Given list
list1 = [1, 2, 3, 4, 5, 6, 7, 8, 9]

# 1. Create numpy array arr1 from list1
arr1 = np.array(list1)

# 2. Create another numpy array arr2 that counts down from 9 to 1
arr2 = np.arange(9, 0, -1)

# 2. Reshape arr1 into a 3x3 matrix.


# 3. Reshape arr2 into a 3x3 matrix.


# 4. Perform element-wise addition between arr1 and arr2 and store the result in result.


# 5. Perform element-wise multiplication between arr1 and arr2 and store the result in product.


# 6. Combine arr1 and arr2 vertically to create a new 6x3 matrix.
# First use the function 'concatenate' and name the matrix stacked_array_cat, 
# then do the same with one of the 'stack' family of functions and name the array stacked_array_stack


# 7. Check whether the two arrays have the same shape and equal values



# Let's repeat the beginning of the exercise with another approach
# 1. Create arr1 from list1

# 2. Create arr2 that counts down from 9 to 1 by reversing arr1
arr2 = np.flip(arr1)

# 3. Change the first value of arr1 to -99

# 4. Now write down how you believe that arr2 looks like! 

# 5. Check how arr2 looks like! Why is it?
import numpy as np

# Given list
list1 = [1, 2, 3, 4, 5, 6, 7, 8, 9]

# 1. Create numpy array arr1 from list1
arr1 = np.array(list1)

# 2. Create another numpy array arr2 that counts down from 9 to 1
arr2 = np.arange(9, 0, -1)

# 2. Reshape arr1 into a 3x3 matrix.
arr1 = arr1.reshape(3, 3)

# 3. Reshape arr2 into a 3x3 matrix.
arr2 = arr2.reshape(3, 3)

# 4. Perform element-wise addition between arr1 and arr2 and store the result in result.
result = arr1 + arr2

# 5. Perform element-wise multiplication between arr1 and arr2 and store the result in product.
product = arr1 * arr2

# 6. Combine arr1 and arr2 vertically to create a new 6x3 matrix.
# First use the function 'concatenate' and name the matrix stacked_array_cat, 
# then do the same with one of the 'stack' family of functions and name the array stacked_array_stack
stacked_array_cat = np.concatenate((arr1, arr2), axis=0)
stacked_array_stack = np.vstack((arr1, arr2))

# 7. Check whether the two arrays have the same shape and equal values
np.array_equal(stacked_array_cat, stacked_array_stack)

# Print the results.
print("arr1:")
print(arr1)

print("\narr2:")
print(arr2)

print("\nresult (addition):")
print(result)

print("\nproduct (multiplication):")
print(product)

print("\nstacked_array:")
print(stacked_array_cat)

# Let's repeat the beginning of the exercise with another approach
# 1. Create arr1 from list1
arr1 = np.array(list1)

# 2. Create arr2 that counts down from 9 to 1 by reversing arr1
arr2 = np.flip(arr1)

# 3. Change the first value of arr1 to -99
arr1[0] = -99

# 4. Now write down how you believe that arr2 looks like! 

# 5. Check how arr2 looks like! Why is it?
arr2
# The array arr2 points to the same computer memory as arr1. python just remembers to reverse its values. 
# Therefore, the first value of arr1 (= -99) becomes the last value of arr2. All other values remain unchanged.

Learning checklist

  • I know what NumPy is and what I need it for.
  • I have an overview of the functionalities that NumPy offers.
  • I have created and manipulated my first NumPy arrays.
  • I know that arrays are mutable, and I am aware that this can lead to confusing behaviour when several references exist for the same data stored in memory. I also know that I can avoid this problem by copying arrays instead of creating multiple references to the same array.