Home > database >  How to calculate the numpy.sum(axis=1) and numpy.angle
How to calculate the numpy.sum(axis=1) and numpy.angle

Time:07-14

From the following test code, it is easy to understand the x.sum() and x.sum(axis=0).

Question 1: How to calculate each value in x.sum(axis=1)?

Question 2: What does the value of np.angle(x, deg=True) mean, and how np.angle works for an array?

test code:

import numpy as np
x = np.arange(27).reshape((3,3,3))
x

output:

array([[[ 0,  1,  2],
        [ 3,  4,  5],
        [ 6,  7,  8]],

       [[ 9, 10, 11],
        [12, 13, 14],
        [15, 16, 17]],

       [[18, 19, 20],
        [21, 22, 23],
        [24, 25, 26]]])

test code:

x.sum()

output:

351

test code:

x.sum(axis=0)

output:

array([[27, 30, 33],
       [36, 39, 42],
       [45, 48, 51]])

test code:

x.sum(axis=1)

output:

array([[ 9, 12, 15],
       [36, 39, 42],
       [63, 66, 69]])

test code:

x.sum(axis=2)

output:

array([[ 3, 12, 21],
       [30, 39, 48],
       [57, 66, 75]])

test code:

y = np.angle(x, deg=True)
y

output:

array([[[0., 0., 0.],
        [0., 0., 0.],
        [0., 0., 0.]],

       [[0., 0., 0.],
        [0., 0., 0.],
        [0., 0., 0.]],

       [[0., 0., 0.],
        [0., 0., 0.],
        [0., 0., 0.]]])

CodePudding user response:

You can think of a 3D array, like the one you have shown here as having the following dimensions (batch, rows, columns).

When using x.sum() you get the result of the sum of all of the values in the 3D array.

When using x.sum(axis=0) you get an array with shape (1,3,3) where you've performed a straight forward matrix addition operation such as:

matrix

When using x.sum(axis=1) you get an array with shape (1,3,3) where you've performed a row-wise addition. In the image above it would be like adding a b, c d, w x, and y z.

Finally, When using x.sum(axis=2) you get an array with shape (1,3,3) where you've performed a column-wise addition. In the image above it would be like adding a c, b d, w y, and x z.

In your last example, this keeps returning 0s because you providing an integer, not a complex number. An example of a complex number would be 2i or 2i 1.

See this example from the numby docs:

>>> np.angle([1.0, 1.0j, 1 1j])               # in radians
array([ 0.        ,  1.57079633,  0.78539816])
>>> np.angle(1 1j, deg=True)                  # in degrees
45.0

visit the numpy docs for more info : https://numpy.org/doc/stable/reference/generated/numpy.angle.html

  • Related