【问题标题】:Checking nan values in a numpy array检查 numpy 数组中的 nan 值
【发布时间】:2015-06-30 08:52:25
【问题描述】:

我从一个 excel 文件中读取了一些列,并将其存储在一个 numpy 数组 col 中。对于 col 中的每个索引 i,我想检查值是否为 nan,如果是 nan,我将删除 col 和另一个数组 x 中的索引 i。我做到了,

workbook = xlrd.open_workbook('well data.xlsx')
sheet=workbook.sheet_by_index(0)
col= sheet.col_values(1,1)
col= np.array (col)
col= col.astype(np.float)
        for i in range (col.shape [0]):
            if (np.isnan(col[i])):
                col=np.delete(col,i)
                x= np.delete(x,i)

我遇到了两种类型的错误, 首先当这个浮点转换存在 col= col.astype(np.float) 时,我得到 ​​p>

    if (np.isnan(col[i])):
IndexError: index out of bounds

其次,如果我删除浮点转换,我会得到这个错误,

    if (np.isnan(col[i])):
TypeError: Not implemented for this type

我知道从单个 numpy 数组中删除 nan 我可以这样做,

x = x[numpy.logical_not(numpy.isnan(x))]

但我的情况不同,我想删除 col 中的 nan 元素,以及 x 中的任何对应元素。例如,如果 col 中的索引 3 为 nan,则应该删除 col 和 x 中的索引 3。此外,在我的情况下,浮点转换是必要的。

这是一个更详细的例子,

这些是初始数组(都具有相似的长度):

col= [16.5, 14.3, 17.42,nan, 13.22, nan]

x= [1, 2, 3, 4, 5, 6]

删除 nans 后,数组应该是,

col= [16.5, 14.3, 17.42, 13.22]

x= [1, 2, 3, 5]

还有一件事,如果我从 .dat 文件中读取列,提供的代码工作得很好,如果我从 excel 中读取列真的很重要吗?

谁能帮我解决这个问题?

谢谢。

【问题讨论】:

  • 请使用示例输入和预期输出更新问题。
  • 我更新了问题

标签: python excel numpy nan


【解决方案1】:

你的第一个想法是正确的。

col= col.astype(np.float)
for i in range (col.shape [0]):
    if (np.isnan(col[i])):
        col=np.delete(col,i)
        x= np.delete(x,i)

几乎是正确的。形状返回对象的总长度,但你必须从 0 到这个长度 -1。所以你的 for 行会是这样的:

for i in range (0, col.shape [0]):

但是由于您要从数组中删除元素,因此在计算这个东西时您可能有一个较小的数组。因此,如果您想访问第五个也是最后一个元素并且之前删除了一个元素,那么 col 将不再有 5 个元素。我建议你在你的柱子上向后循环,像这样

for i in range(col.shape [0]-1, -1, -1):

【讨论】:

  • 非常感谢,但这不起作用,我仍然遇到同样的错误。请问您还有其他解决方案吗?
  • 已编辑,在您的情况下向后循环应该会更好,因为您更改了数组。
猜你喜欢
  • 1970-01-01
  • 2020-09-29
  • 2011-09-25
  • 1970-01-01
  • 2023-03-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-03-21
相关资源
最近更新 更多