有没有办法用相邻值替换列表中的特定值?
Is there a way to replace specific value in a list with the adjacent values?
我的代码应该将缺失值更改为其有效的直接相邻值。但是,它似乎运行不正确,我不太确定错误在哪里。
因此必须将缺失值修正为其相邻值的平均值。但是,如果存在连续的缺失值,则应使用有效的相邻值对其进行更正。仅使用基本的 python 函数,例如 for 循环和 if/else。
data = [1, -999, -999, 3, 4]
missing = -999
for i, num in enumerate(data):
if num == missing:
if [i-1] and [i+1] != missing:
data[i] = (data[i-1] + data[i+1]) / 2
elif [i-1] != missing and [i+1] == missing:
data[i] = data[i-1]
elif [i+1] != missing and [i-1] == missing:
data[i] = data[i+1]
else:
data[i] = data[i]
print(data)
例如:
data = [1, 2, -999, 4, 5], [1, -999, -999, 3, 4], [-999, -999, 3, 4, 5], [-999, -999, -999, -999, -999]
expected output = [1, 2, 3, 4, 5], [1, 1, 3, 3, 4], [3, 3, 3, 4, 5], [-999, -999, -999, -999, -999]
试试下面的代码:
data = [1, 2, 3, -999, -999]
missing = -999
for i, num in enumerate(data):
if (num == missing) and (i not in [0, len(data) - 2, len(data) - 1]):
if (data[i-1] != missing) and (data[i+1] != missing):
data[i] = (data[i-1] + data[i+1]) / 2
elif (data[i-1] != missing) and (data[i+1] == missing):
data[i] = data[i-1]
data[i+1] = data[i+2]
elif (data[i+1] != missing) and (data[i-1] == missing):
data[i] = data[i+1]
data[i-1] = data[i-2]
elif (num == missing) and (i == 0):
if data[i+1] != missing:
data[i] = data[i+1]
else:
data[i] = data[i+2]
elif (num == missing) and (i in [len(data) - 2, len(data) - 1]):
if data[i-1] != missing:
data[i] = data[i-1]
else:
data[i] = data[i-2]
print(data)
输出:
[3, 3.0, 3, 4, 5]
我的代码应该将缺失值更改为其有效的直接相邻值。但是,它似乎运行不正确,我不太确定错误在哪里。
因此必须将缺失值修正为其相邻值的平均值。但是,如果存在连续的缺失值,则应使用有效的相邻值对其进行更正。仅使用基本的 python 函数,例如 for 循环和 if/else。
data = [1, -999, -999, 3, 4]
missing = -999
for i, num in enumerate(data):
if num == missing:
if [i-1] and [i+1] != missing:
data[i] = (data[i-1] + data[i+1]) / 2
elif [i-1] != missing and [i+1] == missing:
data[i] = data[i-1]
elif [i+1] != missing and [i-1] == missing:
data[i] = data[i+1]
else:
data[i] = data[i]
print(data)
例如:
data = [1, 2, -999, 4, 5], [1, -999, -999, 3, 4], [-999, -999, 3, 4, 5], [-999, -999, -999, -999, -999]
expected output = [1, 2, 3, 4, 5], [1, 1, 3, 3, 4], [3, 3, 3, 4, 5], [-999, -999, -999, -999, -999]
试试下面的代码:
data = [1, 2, 3, -999, -999]
missing = -999
for i, num in enumerate(data):
if (num == missing) and (i not in [0, len(data) - 2, len(data) - 1]):
if (data[i-1] != missing) and (data[i+1] != missing):
data[i] = (data[i-1] + data[i+1]) / 2
elif (data[i-1] != missing) and (data[i+1] == missing):
data[i] = data[i-1]
data[i+1] = data[i+2]
elif (data[i+1] != missing) and (data[i-1] == missing):
data[i] = data[i+1]
data[i-1] = data[i-2]
elif (num == missing) and (i == 0):
if data[i+1] != missing:
data[i] = data[i+1]
else:
data[i] = data[i+2]
elif (num == missing) and (i in [len(data) - 2, len(data) - 1]):
if data[i-1] != missing:
data[i] = data[i-1]
else:
data[i] = data[i-2]
print(data)
输出:
[3, 3.0, 3, 4, 5]