The following code:
x = list(range(0,10))
random.shuffle(x)
ind = np.argsort(x)
x[ind]
produces the error: TypeError: only integer scalar arrays can be converted to a scalar index
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.
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.
Method : Using array() + data type indicator This is an inbuilt function in Python to convert to array. The data type indicator “i” is used in case of integers, which restricts data type.
A scalar array is a fixed-length group of consecutive memory locations that each store a value of the same type. You access scalar arrays by referring to each location with an integer starting from zero. In D programs, you would usually use scalar arrays to access array data within the operating system.
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.)
Good answer - but I would add that if the list cannot be converted to a numpy array (i.e. you have a list of string) you cannot slice it with an array of indices as described above. The most straightforward alternative is
[x[i] for i in ind]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With