Predictive Hacks

How to Sum NumPy Arrays by ignoring the NA Values

We can easily get the sum of a NumPy array but if there is any NA value, then the sum is NA too. In this case, we can use the nansum method. For example.

import numpy as np

my_arr = [1,2,np.nan]
my_arr
 
[1, 2, nan]

Let’s try to get the sum.

np.sum(my_arr)
 
nan

As we can see, we got nan. If we want to get the sum of the NumPy array by ignoring the NA values, we can work as follows:

np.nansum(my_arr)
 
3.0

Voilà! We got the required result.

Share This Post

Share on facebook
Share on linkedin
Share on twitter
Share on email

Subscribe To Our Newsletter

Get updates and learn from the best

More To Explore

Python

Image Captioning with HuggingFace

Image captioning with AI is a fascinating application of artificial intelligence (AI) that involves generating textual descriptions for images automatically.

Python

Intro to Chatbots with HuggingFace

In this tutorial, we will show you how to use the Transformers library from HuggingFace to build chatbot pipelines. Let’s