5.1 Python 2D Arrays

5.1.0.1 Lets load some packages

import matplotlib.pyplot as plt
import numpy as np

5.1.0.2 2D arrays: Calculate values

Consider the following 2D data array (called my_data). Lets see what we can do with it?

my_data = np.array([
      [ 0,  1,  2,  3,  4],
      [10, 11, 12, 13, 14],
      [20, 21, 22, 23, 24],
      [30, 31, 32, 33, 34],
      [40, 41, 42, 43, 44]])
my_data.shape        # What is the shape?
## (5, 5)
my_data.min()        # What is the minimum number?
## 0
my_data.max()        # What is the maximum number?
## 44
my_data.mean()       # What is the mean number?
## 22.0
my_data.sum()        # What is the total?
## 550

5.1.0.3 2D arrays: Select rows & columns

my_data = np.array([
      [ 0,  1,  2,  3,  4],
      [10, 11, 12, 13, 14],
      [20, 21, 22, 23, 24],
      [30, 31, 32, 33, 34],
      [40, 41, 42, 43, 44]])

We can easily select rows and columns of the 2D array.

Here is how

my_data[0,:]  # Select me ROW 0 and ALL COLUMNS
## array([0, 1, 2, 3, 4])
my_data[:,0]  # Select me ALL ROWs COLUMNS 0
## array([ 0, 10, 20, 30, 40])
  • It is important to note that Python counts from 0 to 4.b
  • Read : as ‘ALL’

5.1.0.4 2D arrays: Asking Questions

my_data = np.array([
      [ 0,  1,  2,  3,  4],
      [10, 11, 12, 13, 14],
      [20, 21, 22, 23, 24],
      [30, 31, 32, 33, 34],
      [40, 41, 42, 43, 44]])
Example 1

We can ask questions about the array and select accordingly.

Here are some examples.

my_data < 10 # Where is the data less that 10?
## array([[ True,  True,  True,  True,  True],
##        [False, False, False, False, False],
##        [False, False, False, False, False],
##        [False, False, False, False, False],
##        [False, False, False, False, False]])
my_data[my_data < 10] # Select the values less that 10
## array([0, 1, 2, 3, 4])
Example 2

We can also change the array.

my_copy =  my_data.copy()   # Lets make a copy of my data (We don't want to change the original data)

my_copy[my_copy < 10] = 999 # Change the all values less that 10 to 999

print(my_copy) # Did it work?
## [[999 999 999 999 999]
##  [ 10  11  12  13  14]
##  [ 20  21  22  23  24]
##  [ 30  31  32  33  34]
##  [ 40  41  42  43  44]]