How do I remove NaN values from a NumPy array?
[1, 2, NaN, 4, NaN, 8] ⟶ [1, 2, 4, 8]
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
To remove NaN values from a NumPy array
x:Explanation
The inner function
numpy.isnanreturns a boolean/logical array which has the valueTrueeverywhere thatxis not-a-number. Since we want the opposite, we use the logical-not operator~to get an array withTrues everywhere thatxis a valid number.Lastly, we use this logical array to index into the original array
x, in order to retrieve just the non-NaN values.