TypeError when indexing a list with a NumPy array: only integer scalar arrays can be converted to a scalar index

前端 未结 2 1712
谎友^
谎友^ 2021-01-18 11:39

The following code:

x = list(range(0,10))
random.shuffle(x)
ind = np.argsort(x)
x[ind]

produces the error: TypeError: only integer scalar a

2条回答
  •  渐次进展
    2021-01-18 11:58

    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.)

提交回复
热议问题