python - 如何找到:每列中的第一个非 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 中的最大值0
。99
然而是第一个 !NaN 值,并且确实是该列中的最大值。
解决方案
选项 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):idxmax
与first_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
推荐阅读
- c# - 如何从另一个线程更新数据库
- python - 如何在 sed 命令中使用 format() 字符串函数在花括号中导入值
- bash - Cooldown for a certain command in bash
- node-modules - Gitlab CI:如何从预建图像缓存 node_modules?
- nlp - 使用 textacy/spacy 进行 NLP 总结
- excel - 在 Excel 中,如何将单元格设置为自动更新为今天的日期?
- javascript - 道具数据如何操作
- c# - 在 prism 应用程序 (7.2) 中使用 Microsoft Dependency Injection 的 regionmanager 中没有区域
- angularjs - 如何在ui-grid angular JS中对gridMenu中的元素进行排序
- python - 按钮在 Python Tkinter 中无法正常工作