8: Computing With Numpy: in The Documentation

You might also like

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 2

8: Computing With NumPy

Now that alcohol_consumption consists of numeric values, we can


perform computations on it. NumPy has a few built-in methods that operate
on arrays. You can view all of them in the documentation, but here are a few
important ones:

sum() -- computes the sum of all the elements in a vector, or the sum
along a dimension in a matrix.

mean() -- computes the average of all the elements in a vector, or the


average along a dimension in a matrix.

max() -- computes the maximum of all the elements in a vector, or the


maximum along a dimension in a matrix.

Here's how we could use one of these methods on a vector:

vector = numpy.array([5, 10, 15, 20])


vector.sum()

The code above would add together all of the elements in vector, and result
in 50.

With a matrix, we have to specify an additional keyword argument axis.


The axis dictates which dimension we perform the operation on.1 means
that we want to perform the operation on each row, and 0 means on
each column. Here's an example where an operation is performed across
each row:

matrix = numpy.array([
[5, 10, 15],
[20, 25, 30],
[35, 40, 45]
])
matrix.sum(axis=1)

The code above would compute the sum for each row, resulting in [30, 75,
120].

You might also like