Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 914
Josiah Yoder Avatar asked Aug 01 '18 16:08

Josiah Yoder


People also ask

How do you convert a list to an array in Python?

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.

What are scalar arrays?

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.


2 Answers

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

like image 54
Josiah Yoder Avatar answered Sep 29 '22 13:09

Josiah Yoder


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]

like image 44
Jacob Stern Avatar answered Sep 29 '22 12:09

Jacob Stern