IndexError:索引1超出了尺寸1的轴1的范围 [英] IndexError: index 1 is out of bounds for axis 1 with size 1

查看:259
本文介绍了IndexError:索引1超出了尺寸1的轴1的范围的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在应用一些处理,例如将矩阵元素从一个矩阵索引值替换为另一个矩阵索引值.效果很好.

I am applying some processing like replacing matrix element from one matrix index value to another. it works fine.

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)

使用ds2 = ds2.groupby(0).mean()的原因是获取相似元素的平均值.当我取消注释时,它可以正常工作.

Reason behind using ds2 = ds2.groupby(0).mean() is getting average value of similar elements. When I uncomment it, it works without error.

版本

Python 2.7.3
numpy - 1.9.2
pandas - 0.15.2

修改

我的主要目标是将ds2中的索引值匹配到ds1中,并将其替换为相应的值,因此输出看起来像

My main goal is to match the index value from ds2 into ds1 and replace it with corresponding value, so the output would look like

ds1_new = [[ 1, 2,  1,  3],
      [ 2, 1,  3,  2],
      [ 2,  0,  1, 3],
      [ 3,  2, 1,  0]]

推荐答案

我敢打赌,这将比您预期的要容易.首先,让ds2成为字典而不是数据框.

I bet this will be easier than you expected. First, let's make ds2 a dictionary rather than a dataframe.

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

现在,我们将只使用ds2直接映射ds1中的所有元素:

Now, we'll just use ds2 to directly map 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

如果要使用0而不是NaN,只需执行ds3.fillna(0).

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

由于某种原因,我无法使它正常工作

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

ds3.applymap( ds2 )

但这可以工作,并且避免了循环循环,尽管语法并不像一系列的语法那么简单:

But this works and avoids the looping over columns, though the syntax is not quite as simple as it is for a series:

ds1.applymap( lambda x: ds2.get(x,0) )

这篇关于IndexError:索引1超出了尺寸1的轴1的范围的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆