我正在寻找用 numpy 中的 NaN 替换数字,并且正在寻找类似 numpy.nan_to_num 的函数,除非相反。
随着处理不同的数组,该数字可能会发生变化,因为每个数组都可以有唯一定义的 NoDataValue。我见过人们使用字典,但数组很大并且充满了正浮点数和负浮点数。我怀疑尝试将所有这些加载到任何东西中来创建密钥效率不高。
我尝试使用以下内容,但 numpy 要求我使用 any()
或 all()
。我意识到我需要明智地迭代元素,但希望内置函数可以实现这一点。
def replaceNoData(scanBlock, NDV):
for n, i in enumerate(array):
if i == NDV:
scanBlock[n] = numpy.nan
NDV 是 GDAL 的无数据值,数组是 numpy 数组。
屏蔽数组是可行的方法吗?
I am looking to replace a number with NaN in numpy and am looking for a function like numpy.nan_to_num
, except in reverse.
The number is likely to change as different arrays are processed because each can have a uniquely define NoDataValue. I have seen people using dictionaries, but the arrays are large and filled with both positive and negative floats. I suspect that it is not efficient to try to load all of these into anything to create keys.
I tried using the following but numpy requires that I use any()
or all()
. I realize that I need to iterate element wise, but hope that a built-in function can achieve this.
def replaceNoData(scanBlock, NDV):
for n, i in enumerate(array):
if i == NDV:
scanBlock[n] = numpy.nan
NDV is GDAL's no data value and array is a numpy array.
Is a masked array the way to go perhaps?
发布评论
评论(2)
A==NDV 将生成一个布尔数组,可用作 A 的索引
A==NDV will produce a boolean array that can be used as an index for A
您还可以使用 np.where 将数字替换为 NaN。
可以获得以下结果
例如,通过
这会创建一个新副本(与
A[A==NDV]=np.nan
不同),但在某些情况下可能有用。例如,如果数组最初是 int 数据类型,则无论如何它都必须转换为 float 数组(因为否则用 NaN 替换值将不起作用),并且np.where
可以处理该问题。You can also use
np.where
to replace a number with NaN.For example, the following result can be obtained via
This creates a new copy (unlike
A[A==NDV]=np.nan
) but in some cases that could be useful. For example, if the array was initially an int dtype, it will have to converted into a float array anyway (because replacing values with NaN won't work otherwise) andnp.where
can handle that.