typeerror: only integer scalar arrays can be converted to a scalar index

Total
0
Shares

Python numpy throws the typeerror: only integer scalar arrays can be converted to a scalar index, when an ordinary list is indexed with scalar index. Generally, its possible with numpy arrays.

Consider this code –

>>> ordinary_list = list(range(2000))
>>> indices = np.random.choice(range(len(ordinary_list)), replace=False, size=500)
>>> print(ordinary_list[indices.astype(int)])

It will throw the integer scalar arrays can only be converted to scalar index error. This is because ordinary_list is not a numpy array but we are indexing it with np.random.choice index. Here indices is not a single index else its an array of 500 values. In simple words, you need to first convert the list to numpy array and then do the indexing operation. So, this code could be written like this –

>>> ordinary_list = list(range(2000))
>>> indices = np.random.choice(range(len(ordinary_list)), replace=False, size=500)
>>> print(np.array(ordinary_list)[indices.astype(int)])

The same error also occurs when we try to use numpy concatenate method. Here we need to pass the arrays as tuple. So, this code is wrong –

>>> identity_matrix = np.eye(2)
>>> np.concatenate(identity_matrix, identity_matrix)

The correct way of using concatenate is –

>>> identity_matrix = np.eye(2)
>>> np.concatenate((identity_matrix, identity_matrix))
array([[1., 0.],
       [0., 1.],
       [1., 0.],
       [0., 1.]])

Some other examples where scalar index error could appear are –

>>> superhero = ["Ironman", "Hulk", "Thor"]
>>> np_array_index_1 = np.array([1])
>>> print(superhero[np_array_index_1])

TypeError: only integer scalar arrays can be converted to a scalar index

These examples will work fine –

>>> superhero = ["Ironman", "Hulk", "Thor"]
>>> np_index_1 = np.array(1) # it is a simple number 1
>>> print(superhero[np_index_1])
Hulk
>>> superhero = ["Ironman", "Hulk", "Thor"]
>>> np_index_2 = np.array([2]).item()
>>> print(superhero[np_index_2])
Thor
>>> np_superhero = np.array(["Ironman", "Hulk", "Thor"])
>>> np_array_index_1 = np.array([1])
>>> print(np_superhero[np_array_index_1])
array(['Hulk'])

    Tweet this to help others

Live Demo

Open Live Demo