gpt4 book ai didi

Python:替换数组中的值

转载 作者:太空狗 更新时间:2023-10-30 00:07:50 24 4
gpt4 key购买 nike

我有一个一维数据集,其中一些没有数据值被设置为 9999。这是一个摘录,因为它很长:

this_array = [   4,    4,    1, 9999, 9999, 9999,   -5,   -4, ... ]

我想用两侧最接近值的平均值替换无数据值,但是由于一些无数据值具有最接近的值,因为也没有数据值,因此替换它们有点困难。即我希望将三个无数据值替换为 -2。我创建了一个循环来遍历数组中的每个标量并测试没有数据:

for k in this_array:
if k == 9999:
temp = np.where(k == 9999, (abs(this_array[k-1]-this_array[k+1])/2), this_array[k])
else:
pass
this_array[k] = temp

但是我需要添加一个 if 函数或方法来获取 k-1 之前或 k+1 之后的值,如果它也等于 9999 例如:

if np.logical_or(k+1 == 9999, k-1 == 9999):
temp = np.where(k == 9999, (abs(this_array[k-2]-this_array[k+2])/2), this_array[k])

可以看出,这段代码会变得困惑,因为最终可能会采用错误的值或以大量嵌套的 if 函数结束。有谁知道实现它的更简洁的方法,因为它在整个数据集中变化很大?

根据要求:如果第一个和/或最后一个点没有数据,最好将它们替换为最近的数据点。

最佳答案

使用 numpy 函数可能有更有效的方法,但这里有一个使用 itertools module 的解决方案:

from itertools import groupby

for k, g in groupby(range(len(this_array)), lambda i: this_array[i] == 9999):
if k:
indices = list(g)
new_v = (this_array[indices[0]-1] + this_array[indices[-1]+1]) / 2
this_array[indices[0]:indices[-1]+1].fill(new_v)

如果最后一个元素或第一个元素可以是 9999,则使用以下内容:

from itertools import groupby

for k, g in groupby(range(len(this_array)), lambda i: this_array[i] == 9999):
if k:
indices = list(g)
prev_i, next_i = indices[0]-1, indices[-1]+1
before = this_array[prev_i] if prev_i != -1 else this_array[next_i]
after = this_array[next_i] if next_i != len(this_array) else before
this_array[indices[0]:next_i].fill((before + after) / 2)

使用第二个版本的例子:

>>> from itertools import groupby
>>> this_array = np.array([9999, 4, 1, 9999, 9999, 9999, -5, -4, 9999])
>>> for k, g in groupby(range(len(this_array)), lambda i: this_array[i] == 9999):
... if k:
... indices = list(g)
... prev_i, next_i = indices[0]-1, indices[-1]+1
... before = this_array[prev_i] if prev_i != -1 else this_array[next_i]
... after = this_array[next_i] if next_i != len(this_array) else before
... this_array[indices[0]:next_i].fill((before + after) / 2)
...
>>> this_array
array([ 4, 4, 1, -2, -2, -2, -5, -4, -4])

关于Python:替换数组中的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13942083/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com