SkuPak
SkuPak

Reputation: 367

Replace numbers with boolean True

I've got a dataframe with a column like this:

df['test'] = [NaN, 1.0, NaN, NaN, NaN, 13.0]

I'd like to replace NaN with False and all the floats with True.

[False, True, False, False, False, True]

I tried:

df['test'].replace(np.nan, False, inplace=True)
df['test'].replace(np.float64, True, inplace=True)

Problem: this replaces NaN correctly but not floats.

Can someone help me please? Thanks!

Upvotes: 0

Views: 524

Answers (2)

Todd
Todd

Reputation: 5385

Here you go. Not the best answer, but one of the ways.

>>> df
   test
0   NaN
1   1.0
2   NaN
3   NaN
4   NaN
5  13.0
>>> df.apply(lambda x: pd.notna(x))
    test
0  False
1   True
2  False
3  False
4  False
5   True
>>> 

Upvotes: 1

YOLO
YOLO

Reputation: 21709

You can use .notna() method

df['test'].notna()

Upvotes: 4

Related Questions