简体   繁体   中英

When making a pandas comparison how to, return np.nan from np.nan>np.nan?

I have the following two dataFrames:

a = pd.DataFrame([[1,2, 3],[4,3,6], [np.nan, 2, np.nan]])
     0  1    2
0  1.0  2  3.0
1  4.0  3  6.0
2  NaN  2  NaN

and

b = pd.DataFrame([[0,1,3],[5,3,5 ],[np.nan, np.nan, np.nan]])
     0    1    2
0  0.0  1.0  3.0
1  5.0  3.0  5.0
2  NaN  NaN  NaN

A comparison of a>b results in:

       0      1      2
0   True   True  False
1  False  False   True
2  False  False  False

I want however, that the output looks like:

     0      1      2
0   True   True  False
1  False  False   True
2   nan    nan     nan

The comparisons of 2>np.nan and np.nan>np.nan should both result in np.nan . (or any other random value, that is different from True and False)

Anything will help!

We need adding a mask

yourdf=a.gt(b).mask(a.isna()|b.isna(),'nan')
Out[153]: 
       0      1      2
0   True   True  False
1  False  False   True
2    nan    nan    nan

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM