If you are in trouble with problem “IndexError: only integers, slices (`:`), ellipsis (`…`), numpy.newaxis (`None`) and integer or boolean arrays are valid indices” when working with indexes in pandas or numpy library, follow our tutorial below to fix it completely.
Reason for “IndexError: only integers, slices (`:`), ellipsis (`…`), numpy.newaxis (`None`) and integer or boolean arrays are valid indices”
This is a common error when you try to access indexes of an array in numpy or the content of columns in pandas incorrectly.
The following examples display common mistakes when everyone work with numpy and pandas.
Mistake with NumPy:
from random import randint import numpy as np def binarySearch(array, x, left, right): if right >= left: middle = (right + left) / 2 if array[middle] == x: return middle elif array[middle] > x: return binarySearch(array, x, left, middle - 1) else: return binarySearch(array, x, middle + 1, right) else: return -1 # Create random array arr = np.random.randint(40, size = 10) # Random select a number in array x = arr[randint(0, len(arr) - 1)] print("My random array:", arr) print("My hidden number:", x) arr = np.sort(arr) print("My sorted array:", arr) a = binarySearch(arr, x, 0, len(arr) - 1) print("Position of my number in sorted array:", a + 1)
When you run the above code, you will get the following error message:
Traceback (most recent call last):
File "code.py", line 28, in <module>
a = binarySearch(arr, x, 0, len(arr)-1)
File "code.py", line 7, in binarySearch
if array[middle] == x:
IndexError: only integers, slices (`:`), ellipsis (`...`), numpy.newaxis (`None`) and integer or boolean arrays are valid indices
Mistake in Pandas:
import pandas as pd import numpy as np array = np.array( [ [1, 1, 1], [2, 4, 8], [3, 9, 27], [4, 16, 64], [5, 25, 125], [6, 36, 216], [7, 49, 343], ] ) column_values = ["number", "squares", "cubes"] df = pd.DataFrame(data = array, columns = column_values) print("My DataFrame:\n", df) print("My squares column\n", df.columns["squares"])
The same error for this above code:
Traceback (most recent call last):
File "code.py", line 19, in <module>
print("My squares column\n", df.columns["square"])
IndexError: only integers, slices (`:`), ellipsis (`...`), numpy.newaxis (`None`) and integer or boolean arrays are valid indices
The solution to the problem
The solution to NumPy’s error
In the example, variable middle
is assigned to the middle index. Obviously, it must be an integer value, but the result of the /
operator is a float number.
There are some methods to receive an integer value for middle
such as using type casting, round number. Simply, we will use the //
operator to get an integer result.
Code:
from random import randint import numpy as np def binarySearch(array, x, left, right): if right >= left: middle = (right + left) // 2 # Using // operator if array[middle] == x: return middle elif array[middle] > x: return binarySearch(array, x, left, middle - 1) else: return binarySearch(array, x, middle + 1, right) else: return -1 # Create random array arr = np.random.randint(40, size = 10) # Random select a number in array x = arr[randint(0, len(arr) - 1)] print("My random array:", arr) print("My hidden number:", x) arr = np.sort(arr) print("My sorted array:", arr) a = binarySearch(arr, x, 0, len(arr) - 1) print("Position of my number in sorted array:", a + 1)
Result:
My random array: [16 36 14 27 33 27 31 16 9 39]
My hidden number: 27
My sorted array: [ 9 14 16 16 27 27 31 33 36 39]
Position of my number in sorted array: 5
You can also try the round()
function:
def binarySearch(array, x, left, right):
if right >= left:
middle = round((right + left) // 2) # Use round() function
if array[middle] == x:
return middle
Or type casting to get the same result:
def binarySearch(array, x, left, right):
if right >= left:
middle = int((right + left) / 2) # Use type casting
if array[middle] == x:
return middle
The solution to Pandas’s error
In this example, people seem to want to access the value of the “squares”
column, but they are wrong. pandas.DataFrame.columns return column labels of the DataFrame
To get the value of columns in DataFrame, you can pass a list of columns to []
to select columns in that order
Syntax:
df[“columns_name”]
You can also access it directly as an attribute.
df.column_name
Code:
import pandas as pd import numpy as np array = np.array( [ [1, 1, 1], [2, 4, 8], [3, 9, 27], [4, 16, 64], [5, 25, 125], [6, 36, 216], [7, 49, 343], ] ) columnValues = ["number", "squares", "cubes"] df = pd.DataFrame(data = array, columns = columnValues) print("My DataFrame:\n", df) print("My squares column\n", df.squares)
Result:
My DataFrame:
number squares cubes
0 1 1 1
1 2 4 8
2 3 9 27
3 4 16 64
4 5 25 125
5 6 36 216
6 7 49 343
My squares column
0 1
1 4
2 9
3 16
4 25
5 36
6 49
Name: squares, dtype: int64
Summary
You have been through our article and know how to solve “IndexError: only integers, slices (`:`), ellipsis (`…`), numpy.newaxis (`None`) and integer or boolean arrays are valid indices”. Hope you understand clearly the purpose of the function and use them correctly.
Maybe you are interested:
- IndexError: index 0 is out of bounds for axis 0 with size 0
- IndexError: too many indices for array in Python
- “unicodedecodeerror: ‘utf8’ codec can’t decode byte 0xa5 in position 0: invalid start byte”

My name is Robert Collier. I graduated in IT at HUST university. My interest is learning programming languages; my strengths are Python, C, C++, and Machine Learning/Deep Learning/NLP. I will share all the knowledge I have through my articles. Hope you like them.
Name of the university: HUST
Major: IT
Programming Languages: Python, C, C++, Machine Learning/Deep Learning/NLP