Skip to content

[Solved] IndexError: boolean index did not match indexed array along dimension 0; dimension is 485 but corresponding boolean dimension is 488

Last Updated on 2022-08-08 by Clay

Problem

Today, when I tracing some source code of model inference, I encountered the problem cannot be executed. The error message as follows:

IndexError: boolean index did not match indexed array along dimension 0; dimension is 485 but corresponding boolean dimension is 488


The most intuitive understanding of this error message is that the corresponding array dimensions are inconsistent.

We understand the point, then we solve the problem.


Problem Reproduce

If you want to make the same problem, you can use a value-array to correspond another boolean-array.

# coding: utf-8
import numpy as np


def main():
    nums = np.array([1, 2, 3, 4, 5])
    bools = np.array([True, False, True])

    print(nums[bools])


if __name__ == "__main__":
    main()


Output:

Traceback (most recent call last):
  File "test.py", line 13, in <module>
    main()
  File "test.py", line 9, in main
    print(nums[bools])
IndexError: boolean index did not match indexed array along dimension 0; dimension is 5 but corresponding boolean dimension is 3


After execution we get an error message similar to the title of the article. Obviously, this is caused by the different lengths.

So the solutions to this problem is:

  1. Print out the shape of array
  2. Adjust two array to the same length

For example, the code like the following will work fine:

# coding: utf-8
import numpy as np


def main():
    nums = np.array([1, 2, 3, 4, 5])
    bools = np.array([True, False, True, True, False])

    print(nums[bools])


if __name__ == "__main__":
    main()


Output:

[1 3 4]

References


Read More

Tags:

Leave a Reply