# Python NumPy For Your Grandma - 4.2 Math Functions

Contents

NumPy provides a variety of math functions like `sum()`, `mean()`, `min()`, `max()`, `floor()`, `round()`, `exp()`, `log()`, and countless others. When you understand how to use one of these functions, you’ll understand how to use nearly all of them. So in this section, we’re gonna dive into the `sum()` function, but everything we discuss will be applicable to a bunch of other math functions.

Here we have a 2d array called squee.

``````import numpy as np
squee = np.array(
[[5.0, 2.0, 9.0],
[1.0, 0.0, 2.0],
[1.0, 7.0, 8.0]]
)
``````

Let’s see how we can use the sum function to sum its elements. If we call `np.sum(squee)` with no other parameters, we get back 35, the sum of all elements in the array.

``````np.sum(squee)
## 35.0
``````

If we set the axis parameter equal to 0, we can sum across axis 0, in other words, calculating column sums.

``````np.sum(squee, axis = 0)
## array([ 7.,  9., 19.])
``````

Alternatively we can set `axis = 1` to calculate row sums.

``````np.sum(squee, axis = 1)
## array([16.,  3., 16.])
``````

In both of these cases, numpy collapses our 2d array into a 1d array, but if you’d rather retain two dimensions, you can set `keepdims = True`.

``````np.sum(squee, axis = 0, keepdims = True)
## array([[ 7.,  9., 19.]])
``````

Now, let’s see what happens if `squee` contains `nan` values.

``````squee[0, 0] = np.nan
np.sum(squee)
## nan
``````

In this case, NumPy returns `nan` because the sum function expects all values to be non-`nan`. In some cases, your data’s going to have `nan` values, and you’re going to want to sum them as if they were 0s. There’s a few ways you can do this.

Your first option is to use the `where` argument to exclude `nan`s. So you could do

``````np.sum(squee, where = ~np.isnan(squee))
## 30.0
``````

Here the `where` argument just needs to be a boolean array that’s either the same size as `squee` or can broadcast to the same size.

Your second option is to use the `nan_to_num()` function which takes an array and replaces `nan` values with some other specified value which by default is 0. So in this case, we could do

``````np.sum(np.nan_to_num(squee))
## 30.0
``````

And then your third option, which is probably my favorite, is to use the `nansum()` function, which works just like `sum()` but it treats `nan`s a 0s.

``````np.nansum(squee)
## 30.0
``````