Python,IndexError: arrays used as indices must be of integer (or boolean) type

Viewed 43879

Iam getting an IndexError: arrays used as indices must be of integer (or boolean) type at the line for pcolormesh, any idea how to handle this.

script:

import numpy as np 
import matplotlib.pyplot as plt
from mpl_toolkits.basemap import Basemap

data = np.loadtxt('out (copie).txt')
lats = data[:,0]
lons = data[:,1]
codg_tec = data[:,2]

m = Basemap(projection = 'merc', llcrnrlon= -9, llcrnrlat=19, urcrnrlon= 12, urcrnrlat= 37,  resolution= 'i')
m.drawcoastlines()

lon, lat = np.meshgrid(lons, lats)
x, y = m(lon, lat)

cb = m.pcolormesh(x, y, np.squeeze(data[codg_tec]) , shading='flat', cmap=plt.cm.jet)
cbar = m.colorbar(cb, location = 'right', pad = '10%')

m.drawmapboundary()
m.drawmapscale()
m.drawmeridians(np.arange(-9,12,5), labels=[False,False,False,True])
m.drawparallels(np.arange(19,38,5), labels=[True,False,False,False])
m.drawstates()
m.drawcountries()

plt.title('CODG-vTEC on 02-01-2015')
plt.show() 

The error:

Traceback (most recent call last):
 File "color.py", line 21, in <module>
  cb = m.pcolor(x, y, data[codg_tec] , shading='flat', cmap=plt.cm.jet)
IndexError: arrays used as indices must be of integer (or boolean) type
2 Answers

the problem was solved just by converting the float array into int array:

lats = data[:,0].astype(int)
lons = data[:,1].astype(int)
codg_tec = data[:,2].astype(int)

As a more precise general answer and to resolve the error correctly in different cases, Remember that the integer index arrays select the elements in a different way than boolean index arrays. To clear it out consider two snippets below:

>>> elems = np.random.randint(10, size=10)
>>> elems
array([7, 6, 6, 7, 1, 6, 3, 1, 1, 2])
>>> intIndcs = np.random.randint(2, size=10)
>>> intIndcs 
array([1, 0, 1, 0, 0, 1, 1, 0, 1, 0])
>>> elems[intIndcs]
array([6, 7, 6, 7, 7, 6, 6, 7, 6, 7])
>>> boolIndcs = intIndcs.astype(bool)
>>> boolIndcs   
array([ True, False,  True, False, False,  True,  True, False,  True,
       False])
>>> elems[boolIndcs]
array([7, 6, 6, 3, 1])

So the conclusion is that as you can see an int array of 0s and 1s does not select elements in the same way as a boolean array of Trues and Falses. For those who are used to C/C++, IMO it's counter-intuitive and should take care of.

Related