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

后端 未结 4 476
终归单人心
终归单人心 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: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.

提交回复
热议问题