8

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.

5
  • 1
    You could also just use np.arange(0,10) instead of list(range(0,10)) Commented Aug 1, 2018 at 16:41
  • Let me get it right. By doing so, the output will still be the same as your original x which is [0,1,2,3,4,5,6,7,8,9]. Do you agree? Commented Aug 1, 2018 at 16:49
  • @Bazingaa That is correct. The point of this question is to illustrate a common way of producing the error "only integer scalar arrays can be converted to a scalar index" Commented Aug 1, 2018 at 18:22
  • @sacul Thanks for the suggestion. I didn't know about that function. The point of this question is to illustrate a common way of producing the error "only integer scalar arrays can be converted to a scalar index" Commented Aug 1, 2018 at 18:24
  • You used to be able to do this. I think it's a python 3 change, and not a numpy change, but I don't know for sure. I came here because I have old code in py2.7 and I traced a bug to range(200)[np.array((119,), dtype=int)], where np.array((119,), dtype=int) is short for index = np.where(some_complicated_thing == some_complicated_other_thing) This worked in py2.7 and in older versions of numpy, as long as the conversion to an integer index was legal. You might be doing this for old habits reasons too. Commented Mar 30, 2021 at 21:07

2 Answers 2

16

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

Sign up to request clarification or add additional context in comments.

Comments

2

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]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.