0

I am trying to teach myself NumPy in Jupyter Notebooks:

I have an array called 'study_minutes'

But when trying to access using study_minutes[1, 0] or study_minutes[(1, 0)], I get an error:

---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-1-0fb6eb80a6ee> in <module>
----> 1 study_minutes[1, 1] = 360

NameError: name 'study_minutes' is not defined

The source code from the tutorial I am using gives the same error,

Any idea why guys? I am stumped

Many thanks,

  • Are you defining `study_minutes` inside a particular cell, and then calling the array later in the same cell? Jupyter can be a tad tricky for newcomers because the cell run times are all interdependent. – Michael Green Jun 07 '20 at 00:48
  • Hi Michael, thanks for your reply - I am not sure as literally first day I have used it - I wish there was a way of uploading the Jupyter file (the one from the tutorial) because even that one doesn't seem correct for me! – trailrunner89 Jun 07 '20 at 00:53

1 Answers1

2

Are you sure is too many indices error? The last NameError is saying that you did not initialize the array. If you still getting the error and you think is due to the too many indices error check this solution

iLuuPii
  • 67
  • 6
  • Thank you iLuuPii, I think the array was initialized here: `study_minutes = np.zeros(100, np.uint16)` Does this look correct? Many thanks – trailrunner89 Jun 07 '20 at 00:56
  • 1
    here's the problem; that's a 1D array but you're calling it as a 2D array. – Michael Green Jun 07 '20 at 01:04
  • This is complete code: Is this still incorrect? `study_minutes = np.array([ study_minutes, np.zeros(100, np.uint16) ]) study_minutes[1][0] = 60 rand = np.random.RandomState(42) fake_log = rand.randint(30, 180, size=100, dtype=np.uint16) fake_log [fake_log[3], fake_log[8]] fake_log[[3, 8]] index = np.array([ [3, 8], [0, 1] ]) fake_log[index] study_minutes = np.append(study_minutes, [fake_log], axis=0) study_minutes[1, 1] = 360` – trailrunner89 Jun 07 '20 at 01:07
  • If you look at your shape by calling `study_minutes.shape` on that initial array, you'll see that you get `(100,)` because of how NumPy is handling the dimensionality internally. If you want to call the index of your 1D array you only need to pass a single variable like `study_minutes[1]` and that'll return a value. – Michael Green Jun 07 '20 at 01:09
  • If you want to instead cast your array to be 2D, you can use a method called "reshape" via something like `np.array([1,2,3]).reshape((1,-1))`, now instead of a 1D shape of `(100,)` NumPy views that as a 2D shape of `(100,1)` – Michael Green Jun 07 '20 at 01:11
  • here's a resource which might help: https://jakevdp.github.io/PythonDataScienceHandbook/02.02-the-basics-of-numpy-arrays.html – Michael Green Jun 07 '20 at 01:13