[Python] Why does axis=0 in np.mean() compute the mean across columns instead of rows?...

Discussão em 'Python' iniciado por Stack, Março 7, 2025.

  1. Stack

    Stack Membro Participativo

    Why does axis=0 in np.mean() compute the mean across columns instead of rows?


    Assume an example array like this:

    import numpy as np

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


    >>> arr
    array([[1, 2, 3],
    [1, 2, 3]])
    >>> arr.shape
    (2, 3)


    Since arr.shape[0] is 2, representing the number of rows, I expected np.mean(arr, axis=0) to compute the mean for each row, but instead, it computes the mean across columns:

    >>> np.mean(arr, axis=0)
    array([1., 2., 3.]) # Mean of each column
    >>> np.mean(arr, axis=1)
    array([2., 2.]) # Mean of each row


    In the documentation, the "axis" parameter is described as:


    "Axis or axes along which the means are computed."
    ​

    I initially assumed that axis=0 would compute row-wise means returning the mean for each row because arr.shape[0] represents rows.

    I am using python 3.10.0 and numpy version 2.2.3

    Am I understanding the documentation wrong ? Could someone help clarify this convention? Why does axis=0 collapse rows instead of columns?

    Continue reading...

Compartilhe esta Página