【问题标题】:Unexpected behavior when tracing index array in python在 python 中跟踪索引数组时出现意外行为
【发布时间】:2017-05-26 17:34:27
【问题描述】:

我在使用 while 循环获取与从一个数组到另一个数组的跟踪量相关的索引量时遇到了一些意外行为。

我的输入代码是:

from numpy import array
from numpy.ma import where as mwhere
from numpy.ma import masked_array, masked
start_pts = array([False, True, False, False, False, False, True, False, False, False, True])
active    = array([True, True, True, True, True, True, True, True, True, True, True])
spline_index = array([0, 0, 0, 0, 1, 1, 1, 2, 2, 2, 2])
pt0     = array([1, 0, 3, 0, 6, 4, 0, 8, 9, 10, 0])
m_a_pt0 = masked_array(pt0, start_pts)

for i in range(3):
    # start pt
    pt = mwhere((spline_index[active] == i) & (start_pts[active] == 1))
    print pt
    while pt[0]:
        pt = mwhere((spline_index[active] == i) & (m_a_pt0[active] == pt[0]))
        print i, pt

我期待输出:

(array([1]),)
0 (array([0]),)
0 (array([3]),)
0 (array([2]),)
0 (array([], dtype=int64,)
(array([6]),)
1 (array([4]),)
1 (array([5]),)
1 (array([], dtype=int64),)
(array([10]),)
2 (array([9]),)
2 (array([8]),)
2 (array([7]),)
2 (array([], dtype=int64),)

但是当 pt = array([0],) 我得到:

(array([1]),)
0 (array([0]),)
(array([6]),)
1 (array([4]),)
1 (array([5]),)
1 (array([], dtype=int64),)
(array([10]),)
2 (array([9]),)
2 (array([8]),)
2 (array([7]),)
2 (array([], dtype=int64),)

但是如果我测试一个值:

test = (array([0]),)
print mwhere((spline_index[active] == 0) & (m_a_pt0[active] == test[0]))

这将返回带有数组的预期元组:

(array([3]),)

当值仍然存在时,为什么我的 while 循环过早退出数组([0])?

【问题讨论】:

    标签: python arrays indexing


    【解决方案1】:

    长度为 1 的 Numpy 数组具有其单个元素的真值。参见例如this question。如果要检查数组是否为空,请检查其长度是否为零。

    【讨论】:

    • 谢谢!我试图做一个更“pythonic”的检查,如here 所见,但错过了它对数组无效。
    猜你喜欢
    • 2014-09-19
    • 2022-08-05
    • 2019-10-11
    • 1970-01-01
    • 2013-08-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-10-08
    相关资源
    最近更新 更多