【发布时间】:2020-01-02 22:14:03
【问题描述】:
这是一个与基本原理相关的问题,因此对其他人来说可能看起来很愚蠢,但在这里:
通过阅读the docs 和this post,我了解到如果传递的参数数组是一维数组,np.where() 会为y 返回一个空数组。但是如何检查它是否实际上是一个空数组,而不是None 或NaN?
我已经检查了this post 以检查Noneness,但如果我一开始就无法访问返回值,我会不知道该怎么做。我试图访问这个值(见下面的代码),但我得到一个 IndexError
此外,我对numpy.where() 的内部运作有些困惑。从the docs 它说 np.where() 返回一个 ndarray 但如果我在 Jupyter 上运行它,它会返回一个 tuple。
以下是我使用的代码。 (numpy 版本:numpy==1.15.4)
test_array = np.array([4, 5, 6]) # 1-D array
print(type(test_array))
>>> <class 'numpy.ndarray'>
thres = 6
result = np.where(test_array > thres)
print(type(result))
>>> <class 'tuple'>
与上面的问题有关,如果我尝试访问结果值,
result
>>> (array([], dtype=int64),)
result[0]
>>> array([], dtype=int64)
result[1]
>>> IndexError: tuple index out of range
如果我遗漏了什么,请告诉我!
提前致谢!
【问题讨论】:
-
你看到
Note了吗?您在单输入模式下使用where。为此,它将我们推荐给np.nonzero。我和大多数 SO 用户都对在这种nonzero模式下使用where感到内疚。 -
哦,这很有趣 - 我肯定忽略了
Note并且肯定在没有意识到的情况下使用了np.nonzero...感谢您的洞察力!
标签: python arrays numpy data-structures tuples