當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


Python numpy AxisError用法及代碼示例

本文簡要介紹 python 語言中 numpy.AxisError 的用法。

用法:

exception  numpy.AxisError(axis, ndim=None, msg_prefix=None)

提供的軸無效。

每當一個axis指定的參數大於數組維數。為了與針對舊 numpy 版本編寫的代碼兼容,這引發了混合ValueErrorIndexError對於這種情況,這個異常子類都確保except ValueErrorexcept IndexError語句繼續捕獲AxisError.

參數

axis int 或 str

越界軸或自定義異常消息。如果提供了軸,則還應指定ndim

ndim 整數,可選

數組維數。

msg_prefix str,可選

異常消息的前綴。

例子

>>> array_1d = np.arange(10)
>>> np.cumsum(array_1d, axis=1)
Traceback (most recent call last):
  ...
numpy.AxisError: axis 1 is out of bounds for array of dimension 1

負軸被保留:

>>> np.cumsum(array_1d, axis=-2)
Traceback (most recent call last):
  ...
numpy.AxisError: axis -2 is out of bounds for array of dimension 1

類構造函數通常將軸和數組的維度作為參數:

>>> print(np.AxisError(2, 1, msg_prefix='error'))
error: axis 2 is out of bounds for array of dimension 1

或者,可以傳遞自定義異常消息:

>>> print(np.AxisError('Custom error message'))
Custom error message

屬性

axis 整數,可選

如果提供了自定義異常消息,則為越界軸或 None。這應該是用戶傳遞的軸,在任何歸一化以解決負索引之前。

ndim 整數,可選

如果提供了自定義異常消息,則為數組維數或 None

相關用法


注:本文由純淨天空篩選整理自numpy.org大神的英文原創作品 numpy.AxisError。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。