Why does max() sometimes return nan and sometimes ignores it?

后端 未结 4 467
终归单人心
终归单人心 2020-12-20 15:51

This question is motivated by an answer I gave a while ago.

Let\'s say I have a dataframe like this

import numpy as np
import pandas as pd

df = pd.D         


        
4条回答
  •  -上瘾入骨i
    2020-12-20 16:30

    In the first case you are using the numpy max function, which is aware of how to handle numpy.nan.

    In the second case you are using the builtin max function from python. This is not aware of how to handle numpy.nan. Presumably this effect is due to the fact that any comparison (>, <, == etc.) of numpy.nan with a float leads to False. An obvious way to implement max would be to iterate the iterable (the row in this case) and check if each value is larger than the previous, and store it as the maximum value if so. Since this larger than comparison will always be False when one of the compared values is numpy.nan, whether the recorded maximum is the number you want or numpy.nan depends entirely on whether the first value is numpy.nan or not.

提交回复
热议问题