7.8 NumPy Calculation Methods

  • These methods ignore the array’s shape and use all the elements in the calculations.
  • Consider an array representing four students’ grades on three exams:
In [1]:
import numpy as np
In [2]:
grades = np.array([[87, 96, 70], [100, 87, 90],
                   [94, 77, 90], [100, 81, 82]])
In [3]:
grades
Out[3]:
array([[ 87,  96,  70],
       [100,  87,  90],
       [ 94,  77,  90],
       [100,  81,  82]])
  • Can use methods to calculate sum, min, max, mean, std (standard deviation) and var (variance)
  • Each is a functional-style programming reduction
In [4]:
grades.sum()
Out[4]:
1054
In [5]:
grades.min()
Out[5]:
70
In [6]:
grades.max()
Out[6]:
100
In [7]:
grades.mean()
Out[7]:
87.83333333333333
In [8]:
grades.std()
Out[8]:
8.792357792739987
In [9]:
grades.var()
Out[9]:
77.30555555555556

Calculations by Row or Column

  • You can perform calculations by column or row (or other dimensions in arrays with more than two dimensions)
  • Each 2D+ array has one axis per dimension
  • In a 2D array, axis=0 indicates calculations should be column-by-column
In [10]:
grades.mean(axis=0)
Out[10]:
array([95.25, 85.25, 83.  ])
  • In a 2D array, axis=1 indicates calculations should be row-by-row
In [11]:
grades.mean(axis=1)
Out[11]:
array([84.33333333, 92.33333333, 87.        , 87.66666667])

©1992–2020 by Pearson Education, Inc. All Rights Reserved. This content is based on Chapter 5 of the book Intro to Python for Computer Science and Data Science: Learning to Program with AI, Big Data and the Cloud.

DISCLAIMER: The authors and publisher of this book have used their best efforts in preparing the book. These efforts include the development, research, and testing of the theories and programs to determine their effectiveness. The authors and publisher make no warranty of any kind, expressed or implied, with regard to these programs or to the documentation contained in these books. The authors and publisher shall not be liable in any event for incidental or consequential damages in connection with, or arising out of, the furnishing, performance, or use of these programs.