python - 获取已排序的 numpy 矩阵或 pandas 数据帧的最后一个非 nan 索引

标签 python pandas numpy

给定一个像这样的 numpy 数组(或 pandas 数据框):

import numpy as np

a = np.array([
[1,      1,      1,    0.5, np.nan, np.nan, np.nan],
[1,      1,      1, np.nan, np.nan, np.nan, np.nan],
[1,      1,      1,    0.5,   0.25,  0.125,  0.075],
[1,      1,      1,   0.25, np.nan, np.nan, np.nan],
[1, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan],
[1,      1,    0.5,    0.5, np.nan, np.nan, np.nan]
])

我希望最有效地检索每一行中的最后一个非 nan 值,因此在这种情况下,我会寻找一个返回如下内容的函数:

np.array([3,
          2,
          6,
          3,
          0,
          3])

我可以尝试 np.argmin(a, axis=1) - 1,但这至少有两个不受欢迎的属性 - 对于不以 nan 结尾的行,它会失败(dealbreaker)并且它不会“惰性评估”并在达到给定行中的最后一个非 nan 值后停止(这与“必须正确”条件无关紧要)。

我想有一种方法可以用 np.where 做到这一点,但是除了计算每一行的所有元素之外,我看不到一种明显优雅的方法来重新排列输出以获得每行的最后一个索引:

>>> np.where(np.isnan(a))
(array([0, 0, 0, 1, 1, 1, 1, 3, 3, 3, 4, 4, 4, 4, 4, 4, 5, 5, 5]),
 array([4, 5, 6, 3, 4, 5, 6, 4, 5, 6, 1, 2, 3, 4, 5, 6, 4, 5, 6]))

最佳答案

此解决方案不需要对数组进行排序。它只返回轴 1 上的最后一个非 nan 项。

(~np.isnan(a)).cumsum(1).argmax(1)

关于python - 获取已排序的 numpy 矩阵或 pandas 数据帧的最后一个非 nan 索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41111052/

相关文章:

Python 不直观的成员变量行为

python - 有没有办法打印字符/使用 python 中的 print 函数?

python - 如何修复 numpy 浮点运算产生不精确结果的问题?

python - 尝试打开 .csv 文件时出现 "Initializing from file failed"错误(这根本不应该有问题)

python - Numpy 和 CGI​​ 的问题

python - 在同一地址分配的数组 Cython + Numpy

python - 将文本文件转换为Python字典

python - 如何将 html 表转换为 pandas 数据框

python - 如何在 Theano 中分配/更新张量共享变量的子集?

python - 使用嵌套循环在 while 循环中显示特定值?