如何在列表或数组中找到最后一个有效值的索引

How to find the last valid value's index in list or array

我想找到最后一个有效值。 我找到了一些数据框代码,但找不到列表或数组的代码

List = [nan, 1, 4, 6, 8, 122, 12, 34, 54, nan, nan, nan,nan, nan]

结果应如下所示:

print(some_function_for_last_valid_index(List))
output : 8

(输出是一个索引)

您可以过滤掉所有 nan 值,然后 return 最后一项。要实现它,您可以使用 build-in 函数 filter

new_list = list(fileter(lambda x: x != 'nan', old_list))
print(new_list[-1])

但我不知道为什么在您的示例中您希望输出为 7

这是一种方法

例如:

import numpy as np
lst = [np.nan, 1, 4, 6, 8, 122, 12, 34, 54, np.nan, np.nan, np.nan,np.nan, np.nan]
lst = [i for i in lst if not np.isnan(i)]
#or lst = filter(lambda x: np.isfinite(x), lst)
print(len(lst)) #8
nan = 'nan'
List = [nan, 1, 4, 6, 8, 122, 12, 34, 54, nan, nan, nan,nan, nan]

for i in range(len(List)-1,0,-1):
    if List[i] != nan:
        print(i)
        break

输出:

8

另一个解决方案:

while List and List[-1] is nan: List.pop()
print(len(List)-1)

输出:

8