简体   繁体   English

Python:用相邻的数据点替换列表中的元素

[英]Python: Replacing elements in the list with adjacent data points

I currently have a list like this:我目前有一个这样的列表:

A = [1, 2, "NaN", 4, 5,"NaN"]

If an element is null, I would like to replace it with the average value of adjacent values so A[3] would be replaced by 3 (2+4/2).如果一个元素是 null,我想用相邻值的平均值替换它,因此 A[3] 将替换为 3 (2+4/2)。

If there is only one adjacent value as shown by A[5], then return the one adjacent value itself.如果 A[5] 所示只有一个相邻值,则返回一个相邻值本身。

Desired output:所需的 output:

A = [1, 2, 3, 4, 5, 5]

I'm sure there is a better way, but here is one way to do it.我确信有更好的方法,但这是一种方法。 It handles the case where NaN appears at the end of the list.它处理NaN出现在列表末尾的情况。

Code:代码:

A = [1, 2, "NaN", 4, 5,"NaN"]

for i in range(len(A)):
    if A[i] == "NaN":
        if i == 0: A[i] = A[1]
        elif i == len(A) - 1: A[i] = A[i - 1]
        else: A[i] = (A[i - 1] + A[i + 1]) // 2
        
print(A)

Output: Output:

[1, 2, 3, 4, 5, 5]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM