简体   繁体   English

numpy:二维数组,在第一个索引上运行时出错

[英]Numpy: 2d array, error when running over the first index

I'm facing a problem when trying to assign a specific value to a 100x100 2d array. 尝试为100x100 2d数组分配特定值时遇到问题。 I want it to be zero everywhere except along two segments: first line from the 25th to the 75th and last column from the 25th row to the 75th. 我希望它在所有地方都为零,但沿着两个部分除外:第一行从第25行到第75行,最后一列从第25行到第75行。

I tried doing it using the ": looping", I mean: 我尝试使用“:循环”来执行此操作,我的意思是:

my_array[0][25:75] = 1.
my_array[25:75][99] = 1.

but the second line returns me the error: 但是第二行向我返回错误:

IndexError: index 99 is out of bounds for axis 0 with size 50

As if it was first cutting an array of length 50 (75-25) and then assigning with it. 好像是先切割长度为50(75-25)的阵列,然后分配长度。

Of course I can get what I want using: 当然,我可以得到想要的东西:

for x in xrange(25,75):
    my_array[x][-1] = 1.

But, out of curiosity, how could I get it done with : manipulation? 但是,出于好奇,我如何通过:操作完成它?

Put both array slices inside the same square brackets. 将两个数组切片放在相同的方括号内。 Making your problem smaller so it's easier to show: 使问题更小,因此更容易显示:

>>> my_array = np.zeros((10,10))
>>> my_array[0, 2:7] = 1
>>> my_array[2:7, -1] = 1
>>> my_array
array([[ 0.,  0.,  1.,  1.,  1.,  1.,  1.,  0.,  0.,  0.],
       [ 0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.],
       [ 0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  1.],
       [ 0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  1.],
       [ 0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  1.],
       [ 0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  1.],
       [ 0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  1.],
       [ 0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.],
       [ 0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.],
       [ 0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.]])

What's happening now is that you're requesting a 50-row slice of this array, and then the [99] is trying to get the 99th row of that , but there are only 50. 现在所发生的事情是,你要求这个数组的50排片,然后在[99]正在试图获得的第99排,但只有50。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM