2

I'm running into some unexpected behavior using a while loop to get index quantities related to tracing quantities from one array to another.

My input code is:

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

I am expecting an output of:

(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),)

But instead the while loop exits when pt = array([0],) and I get:

(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),)

But if I test a value where:

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

This returns the expected tuple with array:

(array([3]),)

Why is my while loop prematurely exiting for array([0]), when values still exist?

stagermane
  • 1,003
  • 2
  • 12
  • 29

1 Answers1

2

Numpy arrays with length one have the truth value of their single element. See for instance this question. If you want to check if the array is empty, check if its length is zero.

BrenBarn
  • 242,874
  • 37
  • 412
  • 384
  • Thanks! I was trying to do a more "pythonic" check as seen [here](https://www.quora.com/What-is-the-Pythonic-way-to-check-for-an-empty-set), but missed that it is not valid for arrays. – stagermane May 26 '17 at 18:19