- c - 在位数组中找到第一个零
- linux - Unix 显示有关匹配两种模式之一的文件的信息
- 正则表达式替换多个文件
- linux - 隐藏来自 xtrace 的命令
我正在处理不同数据类型的 numpy 数组。我想知道任何特定数组的哪些元素是 NaN。通常,这就是 np.isnan
的用途。
但是,np.isnan
对数据类型object
(或任何字符串数据类型)的数组不友好:
>>> str_arr = np.array(["A", "B", "C"])
>>> np.isnan(str_arr)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: Not implemented for this type
>>> obj_arr = np.array([1, 2, "A"], dtype=object)
>>> np.isnan(obj_arr)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: ufunc 'isnan' not supported for the input types, and the inputs could not be safely coerced to any supported types according to the casting rule ''safe''
我想从这两个调用中得到的只是np.array([False, False, False])
。我不能只将 try
和 except TypeError
放在对 np.isnan
的调用周围,并假设任何生成 TypeError 的数组
不包含 NaN:毕竟,我希望 np.isnan(np.array([1, np.NaN, "A"]))
返回 np .array([False, True, False])
.
我目前的解决方案是创建一个类型为 np.float64
的新数组,循环遍历原始数组的元素,尝试
将该元素放入新数组(如果失败,将其保留为零),然后在新数组上调用 np.isnan
。然而,这当然是相当慢的。 (至少,对于大型对象数组。)
def isnan(arr):
if isinstance(arr, np.ndarray) and (arr.dtype == object):
# Create a new array of dtype float64, fill it with the same values as the input array (where possible), and
# then call np.isnan on the new array. This way, np.isnan is only called once. (Much faster than calling it on
# every element in the input array.)
new_arr = np.zeros((len(arr),), dtype=np.float64)
for idx in xrange(len(arr)):
try:
new_arr[idx] = arr[idx]
except Exception:
pass
return np.isnan(new_arr)
else:
try:
return np.isnan(arr)
except TypeError:
return False
这个特定的实现也只适用于一维数组,我想不出一个合适的方法来让 for
循环在任意数量的维度上运行。
是否有更有效的方法来确定 object
类型数组中的哪些元素是 NaN?
编辑:我正在运行 Python 2.7.10。
请注意,[x is np.nan for x in np.array([np.nan])]
返回 False
:np.nan
在内存中并不总是与不同的 np.nan
相同的对象。
我不希望 string "nan"
被认为等同于 np.nan
:我希望 isnan(np .array(["nan"], dtype=object))
返回 np.array([False])
。
多维度不是大问题。 (一点点 ravel
-and-reshape
ing 都解决不了。:p)
任何依赖 is
运算符来测试两个 NaN 是否等价的函数并不总是有效。 (如果您认为他们应该这样做,请问问自己 is
运算符实际上做了什么!)
最佳答案
如果您愿意使用 pandas 库,可以使用 pd.isnull 来解决这个问题。 :
pandas.isnull(obj)
Detect missing values (NaN in numeric arrays, None/NaN in object arrays)
这是一个例子:
$ python
>>> import numpy
>>> import pandas
>>> array = numpy.asarray(['a', float('nan')], dtype=object)
>>> pandas.isnull(array)
array([False, True])
关于python - np.isnan 在 dtype "object"的数组上,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36198118/
有时评估积分非常困难,但很容易验证解是否正确。在我看来它至少应该是 np,但我对这个概念的理解是有限的,我可能会遗漏一些东西 编辑:为了清楚起见,我很好奇算法的复杂性,该算法找到函数的反导数以解决不定
我对这三个类别的理解是否正确? 要证明问题 X 是 NP: 表明 X 可以在多项式时间内确定性地得到验证(或者X 可以使用 NTM 解决) 要证明问题 X 是 NP 完全的: 表明 X 可以在多项式时
有什么区别NP , NP-完全和 NP-Hard ? 我知道网上有很多资源。我想阅读你的解释,原因是它们可能与外面的不同,或者有一些我不知道的东西。 最佳答案 我假设您正在寻找直观的定义,因为技术定义
我正在寻找一种方法来检查 numpy 数组是 np.float64 还是 np.float32。这适用于 np.float64: a = np.random.rand(10) if not issub
我知道 np.nanargmin 找到列表中不是 NaN 的最小数字。但是,如果调用数组 [np.nan, np.inf],它会产生 0,这是一个 NaN。我发现这种行为很奇怪,我只是想知道以这种方式
关闭。这个问题不符合Stack Overflow guidelines .它目前不接受答案。 这个问题似乎与 help center 中定义的范围内的编程无关。 . 关闭 8 年前。 Improve
我很好奇使用 np.empty 到底有多大不同?而不是 np.zeros ,以及关于 np.ones 的区别.我运行这个小脚本来对每个创建大型数组所花费的时间进行基准测试: import numpy
在操作矩阵的时候,不同的接口对于矩阵的输入维度要求不同,输入可能为1-D,2-D,3-D等等。下面介绍一下使用Numpy进行矩阵维度变更的相关方法。主要包括以下几种: 1、np.newaxis扩充
除了使用一组 or 语句之外 isinstance( x, np.float64 ) 或 isinstance( x, np.float32 ) 或 isinstance( np.float16 )
我尝试了以下代码,但没有发现 np.dot 和 np.multiply 与 np.sum 之间的区别 这里是 np.dot 代码 logprobs = np.dot(Y, (np.log(A2)).T
我编写了一些程序来更新 numpy在每次迭代中列出并对其进行一些操作。迭代次数取决于时间。例如在 1 秒内,可能有 1000 到 2500 次迭代。这意味着 numpy 列表中的项目对于运行程序 1
我有以下两个数据框: a = pd.DataFrame([[1,2, 3],[4,3,6], [np.nan, 2, np.nan]]) 0 1 2 0 1.0 2 3.0 1
我有一个包含很多非零值的数组。当我使用以下方法计算非零项目总数时,我得到了 2 个不同的结果: 1) non_zero_weights = np.any(np.not_equal(lr_l1.coef
我对这么多int有点挣扎cython 中的数据类型。 np.int, np.int_, np.int_t, int 我猜 int在纯python中相当于np.int_ , 那么 np.int 在哪里来
如果您要选择以下三种初始化零数组的方法之一,您会选择哪一种以及为什么? my_arr_1 = np.full(size, 0) 或 my_arr_2 = np.zeros(size) 或 my_arr
我正在使用 np.select 根据应用于其他列的多个条件创建一个新列。这是一个简单的例子: df = pd.DataFrame({'A': [0, 3, 4], 'B': [10, 0, 2]})
我正在使用 np.select 根据应用于其他列的多个条件创建一个新列。这是一个简单的例子: df = pd.DataFrame({'A': [0, 3, 4], 'B': [10, 0, 2]})
我正在读这个code ,用于从头开始实现线性回归: # convert from data frames to numpy matrices X = np.matrix(X.values) y = n
我正在解压缩具有许多不同数据类型的大型二进制文件 (~1GB)。我正处于创建循环以隐藏每个字节的早期阶段。我一直在使用 struct.unpack,但最近认为如果我使用 numpy 它会运行得更快。然
我需要从依存分析树中提取形式为 NP-VP-NP 的三元组,作为 Stanford Parser 中词汇化分析的输出。 执行此操作的最佳方法是什么。例如如果解析树如下: (ROOT (S
我是一名优秀的程序员,十分优秀!