Brian Smith
Brian Smith

Reputation: 1353

Remove nan from list if some of the elements are data-frame

I have below list

import pandas as pd
import numpy as np
dat = pd.DataFrame({'name' : ['A', 'C', 'A', 'B', 'C'], 'val' : [1,2,1,2,4]})
List = [dat, np.nan, dat, np.nan, np.nan]
List

I want to retain only those elements where they are not nan.

There is a similar discussion in How can I remove Nan from list Python/NumPy, but it is only applicable if all elements are scalar.

Is there any way to remove nan if some elements are matrix/dataframe?

Upvotes: 1

Views: 127

Answers (1)

Quang Hoang
Quang Hoang

Reputation: 150785

You can do:

[x for x in List if isinstance(x, pd.DataFrame)]

If you insist on filtering on filter out nan only, then remember that it is a float instance, so:

[x for x in List if not(isinstance(x, float) and np.isnan(x))]

Upvotes: 1

Related Questions