由于本人在实际应用中遇到了有关 numpy.sum() 函数参数 axis 的问题,这里特来记录一下。也供大家参考。

示例

代码如下:

import numpy as np

array = np.array([[1, 1, 1, 1],
                  [2, 2, 2, 2]])

sum_x = np.sum(array, axis=0)
sum_y = np.sum(array, axis=1)
sum_z = np.sum(array, axis=-1)
print("The value of sum_x is: ")
print(sum_x)
print("The value of sum_y is: ")
print(sum_y)
print("The value of sum_z is: ")
print(sum_z)
"""
The value of sum_x is: 
[3 3 3 3]
The value of sum_y is: 
[4 8]
The value of sum_z is: 
[4 8]
"""

总结

可以看到,axis=0 表示沿着 y 轴方向加和所有元素,或者说保留 x 轴向的元素。axis=1 表示沿着 x 轴方向加和所有元素,或者说保留 y 轴向的元素。而 axis=-1 在当前这个二维数组的例子中,表示的含义与设定 axis=1 一致,而如果是三维数组的情况下,那么 axis=-1 应该与设定 axis = 2 所表示的含义一致,但是无论是二维还是三位数组的情况,axis=-1 表示的均是沿着 x 轴方向加和所有元素。

类似的坐标轴问题可以查看这篇------numpy数组的坐标轴问题

原文地址:https://blog.csdn.net/u011699626/article/details/120952744

相关文章:

  • 2021-08-28
  • 2022-12-23
  • 2022-01-09
  • 2021-11-24
  • 2021-09-09
  • 2021-05-31
猜你喜欢
  • 2023-03-20
  • 2021-09-21
  • 2022-12-23
  • 2021-11-14
相关资源
相似解决方案