使用NumPy数组索引列表时发生TypeError:只能将整数标量数组转换为标量索引 [英] TypeError when indexing a list with a 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数组索引列表时发生TypeError:只能将整数标量数组转换为标量索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!