Python index x is out bounds for axis 0 size of n

Question:

Hey guys trying to attempt to create my own basic hockey analytic program. While trying to get all my information I gave been stumped by this error. Tried looking a bunch of things up and nothing seemed to work for me. I am new to using pandas and numpy. Any help would be much appreciated , thank you!!

import numpy as np


nyr_sched = nhl2021_22_sched[(nhl2021_22_sched['home_team'] == 'NYR') | (nhl2021_22_sched['away_team'] == 'NYR')]
nyr_sched

for game in nyr_sched:
    nyr_GID = nyr_sched['game_id']

nyr_GID = np.array(nyr_GID)
nyr_GID.tolist()
nyr_GID

Which prints array([2021020004, 2021020011, 2021020023, 2021020035, 2021020059,...])

But I run into a problem here.

for i in nyr_GID:
    nyr_GID[i] = nyr_GID[i][5:]
    print("Game {} ID is {}".format(i, nyr_GID[i]))

I am looking to remove the first 5 numbers from each ID in the list so instead of 202102004 it is 20004.
However I get an error stating I am trying to access the 20212004 index. Here is the error:

IndexError                                Traceback (most recent call last)
/var/folders/v8/z9h_xhmj1t38rzq1351q_my40000gn/T/ipykernel_13046/4170336391.py in <module>
      1 count = 0
      2 for i in nyr_GID:
----> 3     nyr_GID[i] = nyr_GID[i][5:]
      4     print("Game {} ID is {}".format(i, nyr_GID[i]))

IndexError: index 2021020004 is out of bounds for axis 0 with size 82
Asked By: bildungsroman11

||

Answers:

Try:

for i in range(len(nyr_GID)):
    nyr_GID[i] = str(nyr_GID[i])[5:]
Answered By: harry

The i in

for i in nyr_GID:

refers to the elements in nyr_GID.

To get the corresponding indices use :
range(nyr_GID.size)

Tiny code snippet :

test = np.array([234, 345, 456])
for i in test:
  print(i, test[i])

Traceback (most recent call last):   File "<stdin>", line 2, in <module> 
IndexError: index 234 is out of bounds for axis 0 with size 3

#correct version
for i in range(test.size):
    print(i, test[i])

0 234 1 345 2 456

In your code, you’ll also need
str(nyr_GID[i]) to convert the ith element to string

Answered By: abhivij
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.