尝试在numpy数组中使用整数列表时输入错误:只能将整数标量数组转换为标量索引 [英] Type error when trying to use list of integers in numpy array: only integer scalar arrays can be converted to a scalar index
问题描述
以下代码:
x = list(range(0,10))
random.shuffle(x)
ind = np.argsort(x)
x[ind]
产生错误:TypeError:只能将整数标量数组转换为标量索引
produces the error: TypeError: only integer scalar arrays can be converted to a scalar index
请注意,我的问题与问题不同,
numpy数组TypeError:仅整数标量数组可以转换为标量索引,它正在尝试更复杂的东西。
Note that my problem is different than in the question, "numpy array TypeError: only integer scalar arrays can be converted to a scalar index", which is attempting something more complex.
我在这个问题上的错误是我正在尝试使用普通python列表中的索引列表 - 请参阅我的回答。我预计它比使用范围和随机播放要广泛得多。
My mistake in this question is that I'm trying to use a list of indexes on an ordinary python list -- see my answer. I expect it happens much more broadly than just with using range and shuffle.
推荐答案
问题是我试图索引 x
,一个普通的Python列表,好像它是一个numpy数组。要修复它,只需将 x
转换为numpy数组:
The problem is that I am attempting to index x
, an ordinary Python list, as if it were a numpy array. To fix it, simply convert x
to a numpy array:
x = list(range(0,10))
random.shuffle(x)
ind = np.argsort(x)
x = np.array(x) # This is the key line
x[ind]
(现在我已经两次了。)
(This has happened to me twice now.)
这篇关于尝试在numpy数组中使用整数列表时输入错误:只能将整数标量数组转换为标量索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!