0

As I am new to python programming. I have a problem in the for loop with index error. I have gone through the suggestions that you have given me. My problem is that in the for loop... I didn't get any error with this code below...

for i in range(0,1):

But I have obtained an error if the limit exceeds for example (0,3)

for i in range(0,3):

The error is

IndexError: index 1 is out of bounds for axis 0 with size 1

I have tried to clear out this error and I am not sure that why this error occurs in the for loop if the limits exceed 1.

This is my code:

m=['paketone4000.dump.xlsx','paketone8000.dump.xlsx','paketone12000.dump.xlsx']
fig_name=['j4000','e8000','e12000']

fig=plt.figure(figsize=(6,6)) ##to obtain figure and dimensions of graph

for i in range(0,3):


    #ax=fig.add_subplot(111,projection='3d') ## to have a broad view of figure
    ax = fig.add_axes([0,0,1,1], projection='3d')

    #plot planes
    p = Rectangle((0,-0.7), 4.5,1.4, color="lightgrey", alpha=0.2) #plots the background frame
    ax.add_patch(p)

    art3d.pathpatch_2d_to_3d(p, z=0, zdir="z")

    j=pd.read_excel(m[i])  ##to read the excel file format
    X=j['x'] ## to import the variable on to axes from data set
    Y=j['y']
    Z=j['z']
    #ax.scatter(X,Y,Z,c='g', marker='o') ## to specify the color and shape of point(marker) of the frame

    a=j['x']##import centre of mass from excel file format
    b=j['y']
    c=j['z']

    q1=j['q1'], ##attaining quaternons from excel file format. (comma(,) transformed series to tuple)
    q2=j['q2'],
    q3=j['q3'],
    q4=j['q4'],

    m,n,o,p=np.array([q1,q2,q3,q4]) ## assigning quaternions to variables had converted tuple to float
    Rot_Mat=QtoR(m,n,o,p)

    #cuboid initialising parameters
    center = [a[0], b[0], c[0]] ##centre of the body
    length = 0.3 ##defining length, breadth, height
    width = 0.4
    height = 0.1
    side = np.zeros((8,3))  ###This numpy vector will be used to store the position of the sides

    #rotate the axes and update
    for angle in range(0, 360):
        ax.view_init(90, angle)

    cuboid(center, (length, width, height)) #to execute the defined cuboid

    plt.savefig(fig_name[i])
    plt.clf()
print("\nq1=",m,"q2=",n,"q3=",o,"q4=",p)
print('\nRotation Matrix=',Rot_Mat)
print ("\nCenter = \n",center)

My expected result is that I want to remove the error that was obtained and I am interested in to know why that error occurred when end limit is greater than one.

2 Answers2

2

You're using the name m for two different variables in your code. At the top of the file you use it to create a list of filenames, which you read in the loop. But later in the loop, you reassign it with this line:

m,n,o,p=np.array([q1,q2,q3,q4])

That causes the error when you try to read later files, as the new m value doesn't contain what the code expects (and may not be the expected size).

You should use two different variable names. This kind of issue suggest that it might be a good idea to use longer, more descriptive variable name, as you are a lot less likely to have this kind of random namespace collision with names like filenames and first_quaternion (or whatever).

I'd also suggest using range(len(m)) so that if you change the size of the list at some future time, you won't need to remember to also change the hard-coded range size.

Blckknght
  • 100,903
  • 11
  • 120
  • 169
  • Ya, This may be the case. I have edited m to packet as you can see now in the code. At this point, i am obtaining an error `center = [a[i], b[i], c[i]] ##centre of the body File "pandas\_libs\hashtable_class_helper.pxi", line 964, in pandas._libs.hashtable.Int64HashTable.get_item KeyError: 1 –` – NUTAKKI PRADEEP CHAKRAVARTHI Jul 07 '19 at 21:11
0

An image for this code execution. How about you try replacing

for i in range(0, 5):

with

for i in range(len(m)):

EDIT: Does this work?

m=['paketone4000.dump.xlsx','paketone8000.dump.xlsx','paketone12000.dump.xlsx']
fig_name=['j4000','e8000','e12000']

fig=plt.figure(figsize=(6,6)) ##to obtain figure and dimensions of graph

for index, i in enumerate(m):


    #ax=fig.add_subplot(111,projection='3d') ## to have a broad view of figure
    ax = fig.add_axes([0,0,1,1], projection='3d')

    #plot planes
    p = Rectangle((0,-0.7), 4.5,1.4, color="lightgrey", alpha=0.2) #plots the background frame
    ax.add_patch(p)

    art3d.pathpatch_2d_to_3d(p, z=0, zdir="z")

    j=pd.read_excel(i)  ##to read the excel file format
    X=j['x'] ## to import the variable on to axes from data set
    Y=j['y']
    Z=j['z']
    #ax.scatter(X,Y,Z,c='g', marker='o') ## to specify the color and shape of point(marker) of the frame

    a=j['x']##import centre of mass from excel file format
    b=j['y']
    c=j['z']

    q1=j['q1'], ##attaining quaternons from excel file format. (comma(,) transformed series to tuple)
    q2=j['q2'],
    q3=j['q3'],
    q4=j['q4'],

    m2,n,o,p=np.array([q1,q2,q3,q4]) ## assigning quaternions to variables had converted tuple to float
    Rot_Mat=QtoR(m2,n,o,p)

    #cuboid initialising parameters
    center = [a[0], b[0], c[0]] ##centre of the body
    length = 0.3 ##defining length, breadth, height
    width = 0.4
    height = 0.1
    side = np.zeros((8,3))  ###This numpy vector will be used to store the position of the sides

    #rotate the axes and update
    for angle in range(0, 360):
        ax.view_init(90, angle)

    cuboid(center, (length, width, height)) #to execute the defined cuboid
    amount_of_files_to_rename=index
    new_names = [i*1000 for i in range(4*amount_of_files_to_rename)[::4]]
    for i in new_names:
        plt.savefig('packetone {}.jpg'.format(i))

    #plt.savefig(fig_name[b])
    #plt.clf()       
print("\nq1=",m2,"q2=",n,"q3=",o,"q4=",p)
print('\nRotation Matrix=',Rot_Mat)
print ("\nCenter = \n",center)
Oleg Vorobiov
  • 482
  • 5
  • 14
  • sorry to say, even though the same error `File "D:/Thesis/Excel/New1-all.py", line 143, in j=pd.read_excel(m[i]) ##to read the excel file format IndexError: index 1 is out of bounds for axis 0 with size 1`. Any other suggestion where the mistake is going on. – NUTAKKI PRADEEP CHAKRAVARTHI Jul 07 '19 at 20:47
  • maybe it's a problem with your exel? – Oleg Vorobiov Jul 07 '19 at 20:48
  • If that is the case then i shouldn't get the image for the first file of excel. In this i am obtaining image for `m[0]` – NUTAKKI PRADEEP CHAKRAVARTHI Jul 07 '19 at 20:50
  • The error is at....`File "D:/Thesis/Excel/New1-all.py", line 162, in center = [a[index], b[index], c[index]] ##centre of the body` with `File "pandas\_libs\hashtable_class_helper.pxi", line 964, in pandas._libs.hashtable.Int64HashTable.get_item KeyError: 1`. I have changed the line from your code to this `plt.savefig(fig_name[index]) plt.clf()` – NUTAKKI PRADEEP CHAKRAVARTHI Jul 07 '19 at 21:07
  • Any other suggestion to this question my dear? – NUTAKKI PRADEEP CHAKRAVARTHI Jul 07 '19 at 21:12
  • i edited that line, try it now, it seems to me that `a`, `b` and `c` are lists/tuples with `len=1` – Oleg Vorobiov Jul 07 '19 at 21:13
  • Before that only i have also seen that you have placed the `a[index]` in `center` of which i wanted to say you. Sorry, i have just making attempts and then finalised before you have done. Now, i am writing to give you a response for your valuable time. – NUTAKKI PRADEEP CHAKRAVARTHI Jul 07 '19 at 21:23
  • `m=['paketone4000.dump.xlsx','paketone8000.dump.xlsx','paketone1400000.dump.xlsx'] fig_name=['i4000','i8000','i12000']` As you can see in the code m, fig_name. If i want to keep these files in one folder and the image names should be automatic named then how can i do this? The execution must be one file after other as the above code is executed – NUTAKKI PRADEEP CHAKRAVARTHI Jul 13 '19 at 16:15
  • i honestly don't understand what you are trying to achieve, can you elaborate on what you want from your code? – Oleg Vorobiov Jul 15 '19 at 18:52
  • According to my code an excel file can create an image. So, rather than giving file names in `m` and image names in `fig_name`. I want import one after other excel file from a folder and then it has to create its own image name for the particular excel file which has to be saved in other folder. – NUTAKKI PRADEEP CHAKRAVARTHI Jul 15 '19 at 20:57
  • do you have a picture per excel file, or `n` number of pictures per excel file? – Oleg Vorobiov Jul 16 '19 at 09:49
  • i have created a code for excel files `import re from os import listdir from os.path import isfile, join mypath = "C:/Nutakki/All_set/excel files/episode0/" m = [f for f in listdir(mypath) if isfile(join(mypath, f))] pattern = re.compile(r"\d+") m = sorted(m, key = lambda m : int(pattern.findall(m)[0]) ) print(m)` rather than giving names as a list. In the same manner the image should be saved with different names. – NUTAKKI PRADEEP CHAKRAVARTHI Jul 16 '19 at 10:51
  • if you don't care about the image name, just make it random, example: `import random new_name = random.randint(0, 9999999)` – Oleg Vorobiov Jul 16 '19 at 11:32
  • what is b in code line ` plt.savefig(fig_name[b])` where did you assigned `b`? – NUTAKKI PRADEEP CHAKRAVARTHI Jul 16 '19 at 13:06
  • Instead of this ``plt.savefig(fig_name[b])``, i have added this ``plt.savefig(fig_name[index])``. But the problem is that it gives index 350 instead of 351 when you ``print(index)``. – NUTAKKI PRADEEP CHAKRAVARTHI Jul 16 '19 at 14:51
  • list's index starts with 0 and ends with `len(list)-1` – Oleg Vorobiov Jul 16 '19 at 16:44
  • ok, Thank you. Let me see. what about previous question in comment. – NUTAKKI PRADEEP CHAKRAVARTHI Jul 16 '19 at 18:11
  • for the names you can try something like this: `new_names = [i for i in range(4000*amount_of_files)[::4000]]` – Oleg Vorobiov Jul 17 '19 at 11:14
  • I haven't understood your recent comment. I have tried like this ``plt.savefig('packetone {0}.jpg'.format(index))`` which worked well but it attains names as follow: `packetone 0.jpg, packetone 1.jpg, packetone 2.jpg......` but i required like this format `packetone 0.jpg, packetone 4000.jpg, packetone 8000.jpg,....` What have to be changes in my code line? – NUTAKKI PRADEEP CHAKRAVARTHI Jul 17 '19 at 15:25
  • `new_names = [i*1000 for i in range(4*amount_of_files_to_rename)[::4]]` <- this generates a list of new names(0, 4000, 8000 and so on) based on the ` amount_of_files_to_rename` how you use it is on you :), but i recommend you do it in a new(separate) `for` loop, something like this: `for i in new_names: plt.savefig('packetone {}.jpg'.format(i))` – Oleg Vorobiov Jul 17 '19 at 18:37
  • Ya, it works good. If i have a doubt then i will contact you. Now the images are saved in same folder but I am unable to save this in other folder. – NUTAKKI PRADEEP CHAKRAVARTHI Jul 18 '19 at 08:38
  • ``new_names = [i*1000 for i in range(4*amount_of_files_to_rename)[::4]]``. Can you explain what does `4` represents? – NUTAKKI PRADEEP CHAKRAVARTHI Jul 18 '19 at 09:35
  • in the case of `new_names = [i*1000 for i in range(4*amount_of_files_to_rename)[::4]]`, `[::4]` is the step, for more info [refer to this](https://stackoverflow.com/questions/509211/understanding-slice-notation). – Oleg Vorobiov Jul 18 '19 at 13:45
  • I have added these code lines in your code ``amount_of_files_to_rename=index new_names = [i*1000 for i in range(4*amount_of_files_to_rename)[::4]] for i in new_names: plt.savefig('packetone {}.jpg'.format(i))`` Is that correct? But the plot obtaining is the last image to all the files. – NUTAKKI PRADEEP CHAKRAVARTHI Jul 18 '19 at 18:09
  • is the amount of pictures per `.xlsx` file fixed, or different every time? – Oleg Vorobiov Jul 18 '19 at 18:38
  • It was fixed every time. In the recent comment code. I am obtaining ``.xlsx`` file name to the image file name with perfect match but all the images that are formed are for the last ``.xlsx`` file. – NUTAKKI PRADEEP CHAKRAVARTHI Jul 24 '19 at 09:58
  • it's because you save images with the same names for every `.xlsx` file, i recommend you do this: change `for i in new_names: plt.savefig('packetone {}.jpg'.format(i))` to this `for j in new_names: plt.savefig('packetone {} {}.jpg'.format(index, j))`, also what is the amount of images in your `.xlsx` files? – Oleg Vorobiov Jul 25 '19 at 11:08
  • shall i add the code that you have suggested below this for loop ``for index, i in enumerate(m):`` or outside it? – NUTAKKI PRADEEP CHAKRAVARTHI Jul 26 '19 at 12:12
  • I want to obtain ``paketone0, paketone4000, paketone8000....`` for the excel files ``paketone0.dump, paketone4000.dump, paketone8000.dump...`` but obtaining like this ``paketone0, paketone1, paketone2....`` for the suggested code in the latest comment..... – NUTAKKI PRADEEP CHAKRAVARTHI Jul 26 '19 at 12:55
  • How to save this images in other folder? – NUTAKKI PRADEEP CHAKRAVARTHI Jul 29 '19 at 10:15
  • to save files in a different folder you need to pass not just a name(like `plt.savefig('filename')`) but a full path, relative or absolute, example: `plt.savefig('path/to/your/file/and/name.jpg')`. and for the naming issue... you can try using the name of your `.xlsx` files, example: `plt.savefig(string_with_a_single_xlsx_file_name.split('.', 1)[0]+'.jpg')`. also sorry for the delay, hope this helps. – Oleg Vorobiov Jul 30 '19 at 14:06