【问题标题】:How to replace NaNs in a 1D array with the mean of nearest neighbors? [duplicate]如何用最近邻的平均值替换一维数组中的 NaN? [复制]
【发布时间】:2020-06-04 05:57:23
【问题描述】:

我有一个大型一维数组,其中散布着一些“NaN”值。我想用“NaN”每一侧的值的平均值替换“NaN”值。

这个网站上有很多关于用列或行的平均值替换“NaN”的文档,但我想用它的邻居的平均值替换它。

我编写了以下代码,但它根本没有替换“NaN”值。有人可以告诉我我做错了什么吗?提前致谢。

import numpy as np

lfc=['NaN', 4, 'NaN', 6, 3, 'NaN', 1]

for i in range(0, len(lfc)):
   if lfc[0] == 'nan':
       lfc[0] = lfc[1]
   elif lfc[i] == 'nan':
       lfc[i] = (lfc[i-1] + lfc[i+1]) / 2
   elif lfc[len(lfc)-1] == 'nan':
       lfc[len(lfc)-1] = lfc[len(lfc)-2]

编辑

示例输入:

lfc=['NaN', 4, 'NaN', 6, 3, 'NaN', 1]

预期输出:

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

【问题讨论】:

  • 在示例输入和预期输出中编辑。
  • 你有实际的 NumPy 数组或 Python 列表吗?很难说,因为您分享的内容似乎介于伪代码和实际 Python 之间,请选择一个并编辑您的帖子。
  • 如果邻居本身是“nan”怎么办!!!
  • 帖子已再次编辑-我正在处理 NumPy 数组,而不是列表。至于最近的邻居也是“NaN”,我相信这是循环的第一部分,只要第一个和第二个元素不是 NaN。
  • 您正在混合不相等的 'nan' 和 'NaN'。此外,您需要编辑您的代码,使其使用np.ndarray,而不是list。

标签: python arrays numpy nan mean


【解决方案1】:
# to convert, you can use
lfc=['nan', 4, 'nan', 6, 3, 'nan', 1]
lfc= [np.nan if x == 'nan' else x for x in lfc ]


for i in range(0,len(lfc)):
    if lfc[0] is np.nan:
        lfc[0]=lfc[1]
    elif lfc[i] is np.nan:
        lfc[i]=(lfc[i-1]+lfc[i+1])/2
    elif lfc[len(lfc)-1] is np.nan:
        lfc[len(lfc)-1]=lfc[len(lfc)-2]

 [4, 4, 5.0, 6, 3, 2.0, 1]

注意:如果邻居本身是 NaN,则不考虑。

【讨论】:

    猜你喜欢
    • 2019-03-21
    • 1970-01-01
    • 2013-09-12
    • 2019-04-02
    • 2012-03-21
    • 2013-04-01
    • 2019-04-24
    • 1970-01-01
    • 2014-08-13
    相关资源
    最近更新 更多