pandas 索引错误:索引 1 超出轴 1 的范围,大小为 1
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/30431492/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
IndexError: index 1 is out of bounds for axis 1 with size 1
提问by nlper
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)
Reason behind using ds2 = ds2.groupby(0).mean()is getting average value of similar elements. When I uncomment it, it works without error.
使用背后的原因ds2 = ds2.groupby(0).mean()是获得相似元素的平均值。当我取消注释它时,它可以正常工作。
Version
版本
Python 2.7.3
numpy - 1.9.2
pandas - 0.15.2
Edit
编辑
My main goal is to match the index value from ds2into ds1and replace it with corresponding value, so the output would look like
我的主要目标是匹配来自ds2into的索引值ds1并将其替换为相应的值,因此输出看起来像
ds1_new = [[ 1, 2, 1, 3],
[ 2, 1, 3, 2],
[ 2, 0, 1, 3],
[ 3, 2, 1, 0]]
采纳答案by JohnE
I bet this will be easier than you expected. First, let's make ds2a dictionary rather than a dataframe.
我敢打赌这会比你想象的要容易。首先,让我们制作ds2字典而不是数据框。
ds2 = dict([
[ 4, 1],
[ 5, 3],
[ 6, 1],
[ 7, 2],
[ 4, 1],
[ 8, 2],
[ 9, 3],
[12, 1],
[13, 2],
[22, 3]])
Now, we'll just use ds2to directly map all the elements in ds1:
现在,我们将使用ds2直接映射 中的所有元素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's instead of NaN, just do ds3.fillna(0).
如果你想要0's 而不是 NaN,就做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) )

