Recode a pandas.Series containing 0, 1, and NaN to False, True, and NaN

Kodiologist

Suppose I have a Series with NaNs:

pd.Series([0, 1, None, 1])

I want to transform this to be equal to:

pd.Series([False, True, None, True])

You'd think x == 1 would suffice, but instead, this returns:

pd.Series([False, True, False, True])

where the null value has become False. This is because np.nan == 1 returns False, rather than None or np.nan as in R.

Is there a nice, vectorized way to get what I want?

jezrael

Maybe map can do it:

import pandas as pd

x = pd.Series([0, 1, None, 1])

print x.map({1: True, 0: False})

0    False
1     True
2      NaN
3     True
dtype: object

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

Multiplying Pandas series rows containing NaN

Pandas change Nan Columns values to True or False

Why in numpy `nan == nan` is False while nan in [nan] is True?

How to change consecutive repeating values in pandas dataframe series to nan or 0?

How to sum 2 pandas Series with diffent rows treating NaN as 0

pandas cut a series with nan values

True values become 1 when a value in pandas column is changing to nan

Why is function <= function true, but NaN <= NaN false in ECMAscript

Invert a boolean Series will yield -1 for False and -2 for True in Pandas

Why is NaN === NaN false?

Streaks of True or False in pandas Series

flatten nested list in pandas containing nan

How to check in pandas that column is bool-like (includes either True, False or NaN)?

NaN in pandas Series.tolist() behaves differently from NaN in list

Why typeof 1/0 is NaN?

Series divided by scalar results in NaN/0

Return NaN from indexing operation on a pandas series

Adding series to Pandas dataframe yields column of NaN

Pandas series replace strings with numpy nan

Fastest way to get the mode of a pandas Series with NaN

pandas: unstacking DataFrame to Series causes NaN

Pandas - check if ALL values are NaN in Series

Measuring the duration of NaN gaps in columns of Pandas Series

Pandas - How to identify `nan` values in a Series

Python pandas dataframe fill NaN with other Series

Convert pandas series to int with NaN values

Create set from pandas series with NaN's

Join pandas Dataframe and Series Without NaN values

How can I map True/False to 1/0 in a Pandas DataFrame?