首页 > 解决方案 > 如何找到:每列中的第一个非 NaN 值是否是 DataFrame 中该列的最大值?

问题描述

例如:

      0     1
0  87.0   NaN
1   NaN  99.0
2   NaN   NaN
3   NaN   NaN
4   NaN  66.0
5   NaN   NaN
6   NaN  77.0
7   NaN   NaN
8   NaN   NaN
9  88.0   NaN

我的预期输出是:[False, True]因为 87 是第一个 !NaN 值,但不是 column 中的最大值099然而是第一个 !NaN 值,并且确实是该列中的最大值。

标签: pythonpandasmaxnan

解决方案


选项 a):只需groupby使用first

(可能不是 100%可靠

df.groupby([1]*len(df)).first()==df.max()
Out[89]: 
       0     1
1  False  True

选项 b)bfill

或者使用bfill(用列中的后向值填充任何 NaN 值,那么之后的第一行bfill是第一个非NaN值)

df.bfill().iloc[0]==df.max()
Out[94]: 
0    False
1     True
dtype: bool

选项 c)stack

df.stack().reset_index(level=1).drop_duplicates('level_1').set_index('level_1')[0]==df.max()
Out[102]: 
level_1
0    False
1     True
dtype: bool

选项 d)idxmaxfirst_valid_index

df.idxmax()==df.apply(pd.Series.first_valid_index)
Out[105]: 
0    False
1     True
dtype: bool

选项 e)(来自 Pir)idxmax使用isna

df.notna().idxmax() == df.idxmax()     
Out[107]: 
0    False
1     True
dtype: bool

推荐阅读