Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Compare dataframe but keep the NaN cell

for example I have a dataframe:

0 1 2 3 4 5 6
0 0.493212 0.586246 nan 0.589289 nan 0.629087 0.593872
1 0.568513 0.367722 nan nan nan nan 0.423369
2 0.70054 0.735529 nan nan 0.494135 nan nan
3 nan nan nan 0.338822 0.466331 0.765367 0.83082
4 0.512891 nan 0.623782 0.642438 nan 0.541117 0.92981

If I compare it like:

df >= 0.5  

The result is:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

0 1 2 3 4 5 6
0 0 1 0 1 0 1 1
1 1 0 0 0 0 0 0
2 1 1 0 0 0 0 0
3 0 0 0 0 0 1 1
4 1 0 1 1 0 1 1

How can I keep nan cell ? I mean I need 0.5 > np.nan == np.nan not 0.5 > np.nan == False

>Solution :

IIUC, you can use a mask:

df.lt(0.5).astype(int).mask(df.isna())

output:

     0    1    2    3    4    5    6
0  1.0  0.0  NaN  0.0  NaN  0.0  0.0
1  0.0  1.0  NaN  NaN  NaN  NaN  1.0
2  0.0  0.0  NaN  NaN  1.0  NaN  NaN
3  NaN  NaN  NaN  1.0  1.0  0.0  0.0
4  0.0  NaN  0.0  0.0  NaN  0.0  0.0

If you want to keep the integer type:

out = df.lt(0.5).astype(pd.Int64Dtype()).mask(df.isna()))

output:

      0     1     2     3     4     5     6
0     1     0  <NA>     0  <NA>     0     0
1     0     1  <NA>  <NA>  <NA>  <NA>     1
2     0     0  <NA>  <NA>     1  <NA>  <NA>
3  <NA>  <NA>  <NA>     1     1     0     0
4     0  <NA>     0     0  <NA>     0     0
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading