Numpy array size is shrinking, changing randomly. Index out of bounds error
<p>I am making a large, 3-column 10,000 row array and filling it with random numbers. Then, I am indexing through the rows and deleting rows that don't match my criteria. For some reason, as I index through I get the following error: 
        <code>Traceback (most recent call last):
        File "hw_2.py", line 16, in &lt;module&gt;
        if math.sqrt(cube[y,0]**(2) + cube[y,1]**(2) + cube[y,2]**(2)) &gt; 1: 
        IndexError: index 6786 is out of bounds for axis 0 with size 6786</code></p>

<p>My code is the following:</p>

<pre><code>    import numpy as np
    import math


    #Create a large empty array that can be filled with random numbers
    cube=np.empty([10000,3]);

    #Fill the array with 1x3 (x,y,z) randos in a 1x1 cube
    for x in xrange(0,10000):
       cube[x] = np.random.uniform(-1,1,3) 

    #Consider each coordinate as a vector from the origin; reject all sets of x,y,z vectors whose magnitudes are greater than the radius of the sphere 
    for y in xrange(0,10000):
        if math.sqrt(cube[y,0]**(2) + cube[y,1]**(2) + cube[y,2]**(2)) &gt; 1: 
            cube = np.delete(cube, (y), axis=0)

    #Reject all sets of vectors whose x,y components lay in a circle in the x,y plane of radius 0.25
    for i in xrange(0,10000):
        if cube[i,0] &gt; 0 and cube[i,0]**(2) + cube[i,1]**(2) &lt;= 0.25:
            cube = np.delete(cube, (i), axis=0)

    #Report the average of all coordinates in each plane, this will be the location of the center of mass   
    centermass = np.mean(cube, axis=0)`
</code></pre>

<p>I don't understand why the size of the axis would be less than 10,000 at this point, all 10,000 rows should be filled by the second command.</p>

<p>So you're trying to select certain parts of the array, it seems. There's typically no need to do <code>np.delete</code>, you can use boolean masks instead: </p>

<pre><code>In [34]: np.random.seed(1234)

In [35]: cube = np.random.uniform(-1, 1, size=10000*3).reshape(10000, 3)

In [36]: mask = (cube**2).sum(axis=1) &gt; 0.5

In [37]: mask.shape
Out[37]: (10000,)

In [38]: cube[~mask].shape
Out[38]: (1812, 3)

In [39]: np.mean(cube[~mask], axis=0)
Out[39]: array([  1.39564967e-07,  -2.78051170e-03,  -1.13108653e-03])
</code></pre>

python arrays numpy indexing