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

29,600

Solution 1

You often get this error when you accidentally create a float with one of your calculations of an index value.

In this case:

middles[j] = u[j, ((nx-1)/2)]

...will create a float when (nx-1) is odd. So you could try:

middles[j] = u[j, int(np.round(((nx-1)/2), 0))]

(I'm using np.round here, which is overkill perhaps, but if you start dividing by a number other than 2, then this approach makes much more sense, as it will round up OR down. int() will always floor it.)

Python vs. Matlab

Two things to be aware of:

  1. Matlab defaults to matrix multiplication, whereas NumPy defaults to element-wise multiplication - but that isn't an issue here.
  2. Matlab uses 1-indexing whereas Python (and therefore NumPy) uses 0-indexing. Any code ported from R or Matlab will need indices shifting down by 1.

Solution 2

Never mind ... I see it: you're using a float as an index in your final line of code:

u[j,((nx-1)/2)]

Convert the second index to int:

u[j, int((nx-1)/2)]
Share:
29,600

Related videos on Youtube

LOC12345
Author by

LOC12345

Updated on April 07, 2021

Comments

  • LOC12345
    LOC12345 about 3 years

    I understand that there are other questions with the same error message however I have looked at these and don't understand how it applies to my current situation. So I'm creating a matrix u=np.zeros(shape=(nt,nx)) and then I have also two arrays time=nt*[0] and middles=nx*[0]

    this is the full code I'm trying to implement in regards to plotting the diffusion equation:

    import numpy as np
    import matplotlib.pyplot as plt
    import math
    D=1 #diffusion constant set equal to 1
    C=1 #creation rate of neutrons, set equal to 1
    L=math.pi
    nx=101 #number of steps in x
    nt=10002 #number of timesteps
    dx=L/(nx-1) #step in x
    dt=0.0001 # time step
    Z=(D*dt)/(dx*dx) #constant for diffusion term
    Z1=C*dt #constant for u term
    
    x1=np.arange(-math.pi/2+0.03079992797, 0, 0.03079992797)
    y=np.arange(0.06159985595,math.pi/2, 0.03079992797)
    z = np.hstack((x1, y))
    
    u=np.zeros(shape=(nt,nx))
    time=nt*[0]
    middles=nx*[0]
    u[50,0]=1/dx #setting our delta function
    for j in range(0,nt-1):
     for i in range(2,nx-1):
         u[j+1,i]=Z*(u[j,i+1]-2*u[j,i]+u[j,i-1])+Z1*u[j,i]+u[j,i]
     u[j,1]=0
     u[j,nx-1]=0
     time[j]=dt*j
     middles[j]=u[j,((nx-1)/2)]
     if i==50 or i==100 or i==250 or i==500 or i==1000 or i==10000:
    
        plt.plot(time,middles)
    
     plt.title('Numerical Solution of the Diffusion Equation')
     plt.xlabel('time')
     plt.ylabel('middles')
     plt.show()
    

    however I keep getting this error message seen in the title only integers, slices (:), ellipsis (...), numpy.newaxis (None) and integer or boolean arrays are valid indices The error message is in regards to the middles[j]=u[j,((nx-1)/2)] line I'm trying to convert this code from Matlabe if that explains things somewhat

    • Prune
      Prune over 5 years
      Welcome to StackOverflow. Please read and follow the posting guidelines in the help documentation, as suggested when you created this account. Minimal, complete, verifiable example applies here. We cannot effectively help you until you post your MCVE code and accurately describe the problem. We should be able to paste your posted code into a text file and reproduce the problem you described. You're missing an import, several variable definitions, and the full error message.
    • ajrwhite
      ajrwhite over 5 years
      The error message doesn't match up with the example - can you revise them both so that they align? The error is definitely with the division by 2 creating a float, but it would be good to be able to specifically reference the line.
    • ajrwhite
      ajrwhite over 5 years
      Please also put some spaces around your assignments (=), mathematical operators (+, *, etc.) and after commas so that the code is more readable. You can change your if statement to if i in [50, 100, 250, 500, 1000, 10000]:
    • Prune
      Prune over 5 years
      This question was changed after two answers were posted. You have a new problem. Please revert this to the original question; post the new problem as a new question ... after you have put in the required debugging effort. See this lovely debug blog for help.
    • ajrwhite
      ajrwhite over 5 years
      Also, the Python example is not indented correctly. Please bear in mind the aim of asking questions here is not just to resolve your own problem, but also so that future users can resolve similar problems.
  • LOC12345
    LOC12345 over 5 years
    It's still coming back with an error message saying "list assignment index out of range"
  • LOC12345
    LOC12345 over 5 years
    It's still coming back with an error message saying "list assignment index out of range"
  • Prune
    Prune over 5 years
    Not "still", since it did not produce that problem before, and did not produce that problem in the code you originally posted. You have a different error, which requires a new posting. Please do not change the question except to clarify, especially after you've received valid answers.
  • ajrwhite
    ajrwhite over 5 years
    I've just edited my answer to include a note on Matlab 1-indexing vs Python 0-indexing. Usually a list assignment index out of range error means you've terminated a loop one step too late. Please upvote and accept this answer if it resolves your problem. As Prune says, we fixed the original bug, and you've now encountered a separate one!
  • LOC12345
    LOC12345 over 5 years
    Apologies, this is my first time posting in stack overflow I will keep this in mind for future questions. Thank you for your help
  • M-Chen-3
    M-Chen-3 about 3 years
    This is not an answer; please post this as a comment when you have enough reputation.