Home > Net >  Is there a way to use an array as an index in Python?
Is there a way to use an array as an index in Python?

Time:11-17

I'm trying to speed up my code and right now I have a "for" loop to sum numbers in an array. It's set up like this:

a1=np.zeros(5)
a2=[1,2,3,4,5,6,7,8,9,10]

And what I want to do is sum the values of a2[:5] a2[5:], to end up with

a1=[7,9,11,13,15]

So I've made a loop that goes:

for ii in range(2):
    a1 =a2[5*ii:5*(ii 1)]

However, this is taking really long. Does anyone have any ideas on how to get around this or how to restructure my code?

I want to do:

i=np.range(2)
a1 =a2[5*i:5*(i 1)]

But can't, since you can't use arrays as indices in Python. That's the only other idea I've had besides the loop.

Edit: the 2 here is just an example, in my code I'm planning on having it do this like 50-100 times.

CodePudding user response:

It looks like you would like to add the first half of the list to its second half. This can be accomplished by reshaping the 1D list into a 2D array (2x5) and summing it along the horizontal axis.

np.array(a2).reshape(2,5).sum(axis=0)
# array([ 7,  9, 11, 13, 15])

CodePudding user response:

Depends on what you really want to achieve. but the np.roll function might get the speed you are looking for:

a2 = np.array([1,2,3,4,5,6,7,8,9,10])
a1 = a2[:5]   np.roll(a2, -5)[:5]
  • Related