Rolly
Rolly

Reputation: 37

How to remove rows with nan values in python

I have an array of data with nan values

enter image description here

I want to remove rows with nan values. I want this output:

enter image description here

Leaving only the rows without the nan values.

I tried to use this code

input = input[~np.isnan(input)]

However, the rows did not remove.

I also used

a = input[complete.cases(input), ]

But an error occurred. NameError: name 'complete' is not defined

Upvotes: 1

Views: 1687

Answers (3)

apoorva kamath
apoorva kamath

Reputation: 816

Try this

input = input[~np.isnan(input).any(axis=1)]

any(axis=1) reduces an m*n array to n with an logical or operation on the whole rows.

Upvotes: 0

FLSte
FLSte

Reputation: 668

Given numpy array as

import numpy as np
input = np.array([[1,1,0,np.nan], [1,1,1,30], [1,0,1,np.nan]])

try

output = input[~np.isnan(input).any(axis=1)]

gives output as

[[ 1.  1.  1. 30.]]

Upvotes: 1

EEEEH
EEEEH

Reputation: 779

Dataframe:

   values_1  values_2
0     700.0       NaN
1       NaN     150.0
2     500.0     350.0
3       NaN     400.0
4    1200.0    5000.0

You can try this:

df = df.dropna()
df = df.reset_index(drop=True)

Outputs:

   values_1  values_2
0     500.0     350.0
1    1200.0    5000.0

Upvotes: 1

Related Questions