Home > database >  How to loop through indices in Python?
How to loop through indices in Python?

Time:03-11

I'm trying to run a for loop in python that looks like this:

data = np.linspace(0.5, 50, 10)

output = []
for i in data:
  x = data[i] - data[i 1]
  output.append(data)

but I keep getting the error:

IndexError: only integers, slices (`:`), ellipsis (`...`), numpy.newaxis (`None`) and integer or boolean arrays are valid indices

For reference I want the code to do the following:

  • x1 = x = data[0] - data[1]

  • x2 = x = data[1] - data[2] ...

and output it to the list.

Any help would be really appreciated

CodePudding user response:

There are several things going on here:

  • You are iterating over the actual elements, not their index. To iterate over the indexes you can do something like this for index in range(len(data) - 1)).
  • As shown above, you want to iterrate until len(data) - 1 in order to avoid getting out of bounds.
  • It seems that you are calculating x but eventually append data instead.
  • To achive readable code, it is important to give variables meaningful names (i and x are not meaningfull).
data = np.linspace(0.5, 50, 10)

output = []
for index in range(len(data) - 1):
  result = data[index] - data[index   1]
  output.append(result)

CodePudding user response:

for i in data: loops directly over data, thus i will be each element in data, not its index. If you need the index, use enumerate():

output = []
for i, elem in enumerate(data):
  x = data[i] - data[i 1]
  output.append(data)

However, that won't work, due to an out-of-bounds error that will occur at the very end. Instead, you can use built-in numpy functionality:

output = data[:-1] - data[1:]
print(output)

Output:

array([-5.5, -5.5, -5.5, -5.5, -5.5, -5.5, -5.5, -5.5, -5.5])

Or possible solutions:

np.full(9, -5.5)
np.ones(9) * -5.5

CodePudding user response:

IIUC, you want to calculate the successive differences, but reversed. You can use numpy.diff

np.diff(data[::-1])[::-1]

Other option, shift the array by taking a slice of all but the last/first element and subtract:

data[:-1] - data[1:]

Output: array([-5.5, -5.5, -5.5, -5.5, -5.5, -5.5, -5.5, -5.5, -5.5])

  • Related