当我对两个方向上的正方形numpy数组求和时,形状为何保持不变? [英] Why does the shape remains same when I sum a square numpy array along either directions?

查看:57
本文介绍了当我对两个方向上的正方形numpy数组求和时,形状为何保持不变?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我沿轴= 0(即行)求和时,我期望形状为(1,3).但是,两种情况下的形状都相同.为什么会这样?

I was expecting the shape to be (1,3) when I sum along axis=0 i.e. rows. But the shape remains same in both cases. Why is that?

>>> arr = np.arange(9).reshape(3,3)
>>> arr
array([[0, 1, 2],
   [3, 4, 5],
   [6, 7, 8]])
>>> arr.sum(1)
array([ 3, 12, 21])
>>> arr.sum(1).shape
(3,)
>>> arr.sum(0)
array([ 9, 12, 15])
>>> arr.sum(0).shape
(3,)

推荐答案

numpy.sum返回:

具有与a相同形状的数组,其中删除了指定轴.

An array with the same shape as a, with the specified axis removed.

在两种情况下都移除一个轴后,剩下一个单例元组.

With one axis removed in both cases, you are left with a singleton tuple.

2轴-1个指定轴= 1轴

但是,将keepdims作为True传递时,会得到不同的形状,将所有轴保留在原始数组中,并沿指定轴的长度发生相应的变化:

However, passing keepdims as True in both gives different shapes, retaining all the axes in the original array with a corresponding change of length along the specified axis:

>>> arr.sum(axis=0, keepdims=True)
array([[ 9, 12, 15]])
>>> arr.sum(axis=1, keepdims=True)
array([[ 3],
       [12],
       [21]])

这篇关于当我对两个方向上的正方形numpy数组求和时,形状为何保持不变?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆