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

I apply some processing, such as replacing a matrix element from one matrix index value to another. It works great.

ds1 = [[ 4, 13, 6, 9], [ 7, 12, 5, 7], [ 7, 0, 4, 22], [ 9, 8, 12, 0]] ds2 = [[ 4, 1], [ 5, 3], [ 6, 1], [ 7, 2], [ 4, 1 ], [ 8, 2], [ 9, 3], [12, 1], [13, 2], [22, 3]] ds1= pd.DataFrame(ds1) ds2= pd.DataFrame(ds2) #Processing ds1 by replacing print type(ds2) ds2 = ds2.groupby(0).mean() #.........X print type(ds2) C = np.where(ds1.values.ravel()[:, None] == ds2.values[:, 0]) ds1_new = ds1.values.ravel() ds1_new[C[0]]=ds2.values[C[1], 1] #when I comment line x, it works.Otherwise getting error on this line ds1_new = ds1_new.reshape(4,4) 

The reason for using ds2 = ds2.groupby(0).mean() is to get the average value of similar elements. When I uncomment it, it works without errors.

Version

 Python 2.7.3 numpy - 1.9.2 pandas - 0.15.2 

Edit

My main goal is to compare the index value with ds2 in ds1 and replace it with the corresponding value, so the result will look like

 ds1_new = [[ 1, 2, 1, 3], [ 2, 1, 3, 2], [ 2, 0, 1, 3], [ 3, 2, 1, 0]] 
+2
python numpy pandas
source share
1 answer

I am sure it will be easier than you expected. First, let ds2 dictionary, not a data frame.

  ds2 = dict([ [ 4, 1], [ 5, 3], [ 6, 1], [ 7, 2], [ 4, 1], [ 8, 2], [ 9, 3], [12, 1], [13, 2], [22, 3]]) 

Now we just use ds2 to directly display all the elements in ds1 :

 ds3 = ds1.copy() for i in range(4): ds3[i] = ds3[i].map( ds2 ) 0 1 2 3 0 1 2 1 3 1 2 1 3 2 2 2 NaN 1 3 3 3 2 1 NaN 

If you want 0 instead of NaN, just ds3.fillna(0) .

For some reason, I couldn't get this to work:

 ds3.applymap( ds2 ) 

But this works and avoids looping through columns, although the syntax is not as simple as for the series:

 ds1.applymap( lambda x: ds2.get(x,0) ) 
+1
source share

All Articles