Python Forum

Full Version: Index Error
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
I am trying to run a simple Python 3 program. I am getting at the moment an index error The code is as shown.


import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline

topo = np.loadtxt('topo.asc',delimiter=',')

plt.plot(topo[0,:], label='North')

plt.plot(topo[-1,:],'r--', label='South')

plt.plot(topo[len(topo)/2,:], 'g:', linewidth=3, label='Mid')

plot.title('Topographic profiles')
plot.ylabel('Elevation (m)')
plot.xlabel('<-- West  East -->')
plot.legend(loc = 'lower left')

plt.show()
The error reads as below:
Error:
IndexError Traceback (most recent call last) <ipython-input-4-fba3d9a19be8> in <module> 9 plt.plot(topo[-1,:],'r--', label='South') 10 ---> 11 plt.plot(topo[len(topo)/2,:], 'g:', linewidth=3, label='Mid') 12 13 plot.title('Topographic profiles') IndexError: only integers, slices (`:`), ellipsis (`...`), numpy.newaxis (`None`) and integer or boolean arrays are valid indices
Now I think I see what is wrong.I just do not know how to fix it. In line 11 there is a division by 2. There it it is possible that the index could not be an integer.

Thus the error occurs.

However, what do I do to fix it?

Thanks in advance.

Respectfully,

ErnestTBass
Integer division (the // operator). Note that it truncates the result, which may or may not be what you want.
Sure, I found that out. But, I am unsure as how to
fix his error.

How to fix?

Respectfully,

ErnestTBass
You fix it by replacing the standard division in line 11 with integer division.
Thanks for your help. I will give it try.

Respectfully,

ErnestTBass
You fix it by replacing the standard division in line 11 with integer division.




I am too new to Python 3 to know how to do that. I understand the concept, but I just
do not know the syntax. I could do it i other languages, but not Python.

Any help appreciated. Thanks in advance.

Respectfully,

ErnestTBass