Python IndexError:只有整数、切片 (`:`)、省略号 (`...`)、numpy.newaxis (`None`) 和整数或布尔数组是有效索引

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/44917589/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-20 00:37:07  来源:igfitidea点击:

IndexError: only integers, slices (`:`), ellipsis (`...`), numpy.newaxis (`None`) and integer or boolean arrays are valid indices

pythonnumpy

提问by user824624

I am working on the snippet

我正在处理代码片段

top[0].data[128,0:128] = (fc1[self.keep1.tolist()])[self.keep2[128].tolist()]

keep1 has the data

keep1 有数据

[
  0.0, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0, 11.0, 12.0, 13.0, ...... 114.0, 115.0, 116.0, 117.0, 118.0, 119.0
]

keep2 has the data

keep2 有数据

[ 
   125.  800.  255.  119.  801.  804.  114.  368.  636.  308.  805.  213.
   ......218.   373.
]

I got a problem saying "IndexError: only integers, slices (:), ellipsis (...), numpy.newaxis (None) and integer or boolean arrays are valid indices"

我有一个问题说“IndexError:只有整数、切片 ( :)、省略号 ( ...)、 numpy.newaxis ( None) 和整数或布尔数组是有效索引”

I tried self.keep2[128].tolist().astype(int), but it does say tolist() has no method astype(int)

我试过 self.keep2[128].tolist().astype(int),但它确实说 tolist() 没有方法 astype(int)

how could I solve it?

我怎么能解决呢?

回答by JohanL

Assuming that top[0].data, fc1, self.keep1and self.keep2are all numpyarrays you are making your solution too complicated, when you turn your variables into lists. It is sufficient to do

假设top[0].data, fc1,self.keep1self.keep2都是numpy数组,当您将变量转换为列表时,您的解决方案就会变得过于复杂。做就足够了

top[0].data[128,0:128] = (fc1[self.keep1.astype(int)])[self.keep2[128].astype(int)]

if the dimensions are correct.

如果尺寸正确。

You should also ask yourself why keep1and keep2are floats and not ints to begin with. Are they the result of some float calculation? And in that case, can you be sure they do not have any fractional part?

您还应该问自己为什么keep1和开始时keep2是浮点数而不是整数。它们是一些浮点计算的结果吗?在那种情况下,你能确定它们没有任何小数部分吗?