Numpy数组大小正在缩小,随机变化。索引越界错误

时间:2016-10-17 13:22:32

标签: python arrays numpy indexing

我正在制作一个大的3列10,000行数组并用随机数填充它。然后,我正在索引行并删除不符合我的条件的行。出于某种原因,当我索引时,我得到以下错误:         Traceback (most recent call last): File "hw_2.py", line 16, in <module> if math.sqrt(cube[y,0]**(2) + cube[y,1]**(2) + cube[y,2]**(2)) > 1: IndexError: index 6786 is out of bounds for axis 0 with size 6786

我的代码如下:

    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)) > 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] > 0 and cube[i,0]**(2) + cube[i,1]**(2) <= 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)`

我不明白为什么此时轴的大小会小于10,000,所有10,000行应由第二个命令填充。

1 个答案:

答案 0 :(得分:0)

所以你似乎正试图选择数组的某些部分。通常不需要np.delete,您可以使用布尔掩码:

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) > 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])