如何查找:每列中的第一个非NaN值是否是DataFrame中该列的最大值? [英] How do I find: Is the first non-NaN value in each column the maximum for that column in a DataFrame?
本文介绍了如何查找:每列中的第一个非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值,而不是列0
中的最大值. 99
是第一个!NaN值,并且实际上是该列中的最大值.
My expected output is: [False, True]
since 87 is the first !NaN value but not the maximum in column 0
. 99
however is the first !NaN value and is indeed the max in that column.
推荐答案
选项a):只需使用first
进行groupby
(可能不是100%可靠)
df.groupby([1]*len(df)).first()==df.max()
Out[89]:
0 1
1 False True
选项b):bfill
或使用bfill
(用该列中的向后值填充任何NaN值,然后bfill
之后的第一行是第一个非NaN
值)
Option b): bfill
Or using bfill
(Fill any NaN value by the backward value in the column , then the first row after bfill
is the first not NaN
value )
df.bfill().iloc[0]==df.max()
Out[94]:
0 False
1 True
dtype: bool
选项c):stack
Option 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):idxmax
与first_valid_index
Option d): idxmax
with first_valid_index
df.idxmax()==df.apply(pd.Series.first_valid_index)
Out[105]:
0 False
1 True
dtype: bool
选项e)(来自Pir):idxmax
和isna
Option e)(From Pir): idxmax
with isna
df.notna().idxmax() == df.idxmax()
Out[107]:
0 False
1 True
dtype: bool
这篇关于如何查找:每列中的第一个非NaN值是否是DataFrame中该列的最大值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文