对数组的轴和轴计算的理解

文前总结:用shape理解轴

  1. 理解轴
    2维数组,axis=0,横轴;axis=1,纵轴;如果是3维及以上的多维数组,先最外层,然后一层一层按照先横轴再纵轴的逻辑进行匹配轴。
    直观的图如下:
    2维数组
    3维数组

  2. 计算轴
    以sum方法为例,会发现以哪一个轴为参数计算,该轴变为0(降一个维度)
    如sum应用在2维数组,axis=0,以横轴为参数计算和,则是纵向相加(逐行相加);axis=1,以纵轴为参数计算和,则是横向相加(逐列相加)。
    如sum应用在3维数组,很难描述,请直接看代码,重点关注shape的变化(降一个维度)。

  3. 参考代码

# 2维数组的sum方法
import numpy as np
arr1 = np.array([1,2,3,4,5,6]).reshape(2,3)
print(arr1)
print(arr1.shape)
print()
print(arr1.sum(axis=0))
print(arr1.sum(axis=0).shape)

[[1 2 3]
 [4 5 6]]
(2, 3)

[5 7 9]
(3,) # 此处注意原数组中的axis=0代表的shape2消失

# 3维数组的sum方法
arr2 = np.arange(24).reshape(2,3,4)
print(arr2)
print(arr2.shape)
print()
print(arr2.sum(axis=0))
print(arr2.sum(axis=0).shape)
print()
print(arr2.sum(axis=1))
print(arr2.sum(axis=1).shape)
print()
print(arr2.sum(axis=2))
print(arr2.sum(axis=2).shape)

[[[ 0  1  2  3]
  [ 4  5  6  7]
  [ 8  9 10 11]]

 [[12 13 14 15]
  [16 17 18 19]
  [20 21 22 23]]]
(2, 3, 4)

# 按axis=0进行sum运算
[[12 14 16 18]
 [20 22 24 26]
 [28 30 32 34]]
(3, 4) # 此处注意原数组中的axis=0代表的shape2消失

# 按axis=1进行sum运算
[[12 15 18 21]
 [48 51 54 57]]
(2, 4)  # 此处注意原数组中的axis=1代表的shape3消失

# 按axis=2进行sum运算
[[ 6 22 38]
 [54 70 86]]
(2, 3) # 此处注意原数组中的axis=2代表的shape4消失

以上为初学者理解,贻笑大方,仅供参考

  • 4
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值