Last Updated on 2022-06-08 by Clay
問題描述
今天,當我在閱讀原始程式碼的過程中,我遇到了一段無法執行的程式碼。該程式碼執行時的錯誤訊息如下:
IndexError: boolean index did not match indexed array along dimension 0; dimension is 485 but corresponding boolean dimension is 488
這份錯誤訊息最直觀的理解是:兩兩對應的陣列維度不一致。
知道了這點後,我們就能開始排除問題。
問題重現
要重現類似的問題,可以使用一個數值陣列對應一個布林陣列。
# 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
執行後我們會得到一個與文章標題類似的錯誤訊息。很明顯,這是由於長度不一樣所引起的。
所以這個問題的排除方法就是:
- 印出確認陣列的形式
- 將兩陣列調整至相同長度
比方說像以下程式碼就能正常執行:
# 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
- https://cumsum.wordpress.com/2021/03/07/numpy-indexerror-boolean-index-did-not-match-indexed-array-along-dimension-xx-dimension-is-x-but-corresponding-boolean-dimension-is-y/
- https://stackoverflow.com/questions/72060723/i-am-having-a-userwarning-unknown-classes-when-using-multilabelbinarizer
Read More
- [已解決][Python] 使用 Numpy 判斷時報錯:ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
- [已解決] FutureWarning: Passing (type, 1) or ‘1type’ as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / ‘(1,)type’. _np_qint8 = np.dtype([(“qint8”, np.int8, 1)])