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

后端 未结 4 456
终归单人心
终归单人心 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条回答
  • 2020-12-20 16:18

    The reason is that max works by taking the first value as the "max seen so far", and then checking each other value to see if it is bigger than the max seen so far. But nan is defined so that comparisons with it always return False --- that is, nan > 1 is false but 1 > nan is also false.

    So if you start with nan as the first value in the array, every subsequent comparison will be check whether some_other_value > nan. This will always be false, so nan will retain its position as "max seen so far". On the other hand, if nan is not the first value, then when it is reached, the comparison nan > max_so_far will again be false. But in this case that means the current "max seen so far" (which is not nan) will remain the max seen so far, so the nan will always be discarded.

    0 讨论(0)
  • 2020-12-20 16:19

    the two are different: max() vs df.max().

    max(): python built-in function, it must be a non-empty iterable. Check here: https://docs.python.org/2/library/functions.html#max

    While pandas dataframe -- df.max(skipna=..), there is a parameter called skipna, the default value is True, which means the NA/null values are excluded. Check here: https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.max.html

    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2020-12-20 16:30

    This is due to the ordering of the elements in the list. First off, if you type

    max([1, 2, np.nan])
    

    The result is 2, while

    max([np.nan, 2, 3])
    

    gives np.nan. The reason for this is that the max function goes through the values in the list one by one with a comparison like this:

    if a > b
    

    now if we look at what we get when comparing to nan, both np.nan > 2 and 1 > np.nan both give False, so in one case the running maximum is replaced with nan and in the other it is not.

    0 讨论(0)
提交回复
热议问题