# 轴异常 numpy.exceptions.AxisError

2 篇文章 0 订阅

## 轴异常 numpy.exceptions.AxisError

### 签名

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


### 简介

-ndim ≤ \le axis ≤ \le ndim-1

### 参数

axis

int 类型或 str 类型

ndim

int 类型，可选参数

msg_prefix

str 类型，可选参数

### 属性

axis

int 类型 ，可选属性

ndim

int 类型，可选属性

## 案例

### 轴正向越界 , 以 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 为例

# 传入参数 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)



>>> 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

• 19
点赞
• 4
收藏
觉得还不错? 一键收藏
• 0
评论
07-15 734
08-23 1万+
10-16 805
11-24 2994
04-02 4965
11-26 1万+
06-15 3125

1.余额是钱包充值的虚拟货币，按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载，可以购买VIP、付费专栏及课程。