轴异常 numpy.exceptions.AxisError
签名
exception exceptions.AxisError(axis, ndim=None, msg_prefix=None)
简介
提供的轴非法
当给定的参数 axis
越过了数组维数的界限时应当抛出的异常。继承自 ValueError
和 IndexError
。
-ndim
≤
\le
≤ axis
≤
\le
≤ ndim-1
参数
axis
int
类型或 str
类型
出界的轴序号或者常规的异常说明字符串。如果是 int
类型,那 ndim
也要跟着一起传入。
ndim
int
类型,可选参数
数组的维数
msg_prefix
str
类型,可选参数
异常信息的前缀
属性
axis
int
类型 ,可选属性
越界的轴序号,默认值是 None
ndim
int
类型,可选属性
数组的维数,默认是 None
案例
轴正向越界 , 以 cumsum 为例
cumsum()
函数可以接收 axis
来直接累加进行的轴。当轴序号超过 ndim-1
时,会报错。
>>> import numpy as np
>>> array_2d = np.arange(16).reshape(4,4)
>>> array_2d # 二维数组正向轴序号可以为 0,1
array([[ 0, 1, 2, 3],
[ 4, 5, 6, 7],
[ 8, 9, 10, 11],
[12, 13, 14, 15]])
# 传入参数 axis = 0
>>> np.cumsum(array_2d,axis=0)
array([[ 0, 1, 2, 3],
[ 4, 6, 8, 10],
[12, 15, 18, 21],
[24, 28, 32, 36]])
# 传入参数 axis = 1
>>> np.cumsum(array_2d,axis=1)
array([[ 0, 1, 3, 6],
[ 4, 9, 15, 22],
[ 8, 17, 27, 38],
[12, 25, 39, 54]])
# 传入参数 axis = 2
>>> np.cumsum(array_2d,axis=2)
AxisError Traceback (most recent call last)
...
AxisError: axis 2 is out of bounds for array of dimension 2
轴负向越界,以 cumsum 为例
当轴序号低于 -ndim
时,会报错。
# 传入参数 axis = -1, 相当于最后一根轴,此处为 1
>>> np.cumsum(array_2d,axis=-1)
array([[ 0, 1, 3, 6],
[ 4, 9, 15, 22],
[ 8, 17, 27, 38],
[12, 25, 39, 54]])
# 传入参数 axis = -2
>>> np.cumsum(array_2d,axis=-2)
array([[ 0, 1, 2, 3],
[ 4, 6, 8, 10],
[12, 15, 18, 21],
[24, 28, 32, 36]])
# 传入参数 axis = -3
>>> np.cumsum(array_2d,axis=-3)
AxisError Traceback (most recent call last)
...
AxisError: axis -3 is out of bounds for array of dimension 2
异常类的构造方法
一种是传入轴序号和维数
>>> err1 = np.exceptions.AxisError(2, 1, msg_prefix='轴越界')
>>> err1
numpy.exceptions.AxisError(2, 1)
>>> print(err1)
轴越界: axis 2 is out of bounds for array of dimension 1
一种是传入错误信息
>>> err2 = np.exceptions.AxisError('轴越界了!!!')
>>> err2
numpy.exceptions.AxisError('轴越界了!!!')
>>> print(err2)
轴越界了!!!
源代码
class AxisError(ValueError, IndexError):
__slots__ = ("axis", "ndim", "_msg") # 所有的属性
def __init__(self, axis, ndim=None, msg_prefix=None):
if ndim is msg_prefix is None: # axis 传入字符串
self._msg = axis
self.axis = None
self.ndim = None
else: # axis 传入整数
self._msg = msg_prefix
self.axis = axis
self.ndim = ndim
def __str__(self):
axis = self.axis
ndim = self.ndim
if axis is ndim is None:
return self._msg
else:
msg = f"axis {axis} is out of bounds for array of dimension {ndim}"
if self._msg is not None:
msg = f"{self._msg}: {msg}"
return msg