下面是我生成一个数据框架的代码:

import pandas as pd
import numpy as np

dff = pd.DataFrame(np.random.randn(1,2),columns=list('AB'))

然后我得到了数据框架:

+------------+---------+--------+
|            |  A      |  B     |
+------------+---------+---------
|      0     | 0.626386| 1.52325|
+------------+---------+--------+

当我输入命令时:

dff.mean(axis=1)

我得到:

0    1.074821
dtype: float64

根据pandas的参考,axis=1代表列,我希望命令的结果是

A    0.626386
B    1.523255
dtype: float64

我的问题是:轴在熊猫中是什么意思?


当前回答

我的想法是:Axis = n,其中n = 0,1等意味着矩阵沿该轴折叠(折叠)。所以在一个二维矩阵中,当你沿着0(行)折叠时,你实际上是一次对一列进行操作。对于高阶矩阵也是如此。

这与对矩阵中维数的正常引用不同,其中0 ->行和1 ->列。对于N维数组中的其他维度也是如此。

其他回答

记住轴1(列)与轴0(行)的简单方法之一是您期望的输出。

如果你希望每行都有输出,使用axis='columns', 另一方面,如果你想为每一列输出,你可以使用axis='rows'。

这里的许多答案对我帮助很大!

如果你对Python中的axis和R中的MARGIN的不同行为感到困惑(比如在apply函数中),你可以找到我写的一篇感兴趣的博客文章:https://accio.github.io/programming/2020/05/19/numpy-pandas-axis.html。

从本质上讲:

Their behaviours are, intriguingly, easier to understand with three-dimensional array than with two-dimensional arrays. In Python packages numpy and pandas, the axis parameter in sum actually specifies numpy to calculate the mean of all values that can be fetched in the form of array[0, 0, ..., i, ..., 0] where i iterates through all possible values. The process is repeated with the position of i fixed and the indices of other dimensions vary one after the other (from the most far-right element). The result is a n-1-dimensional array. In R, the MARGINS parameter let the apply function calculate the mean of all values that can be fetched in the form of array[, ... , i, ... ,] where i iterates through all possible values. The process is not repeated when all i values have been iterated. Therefore, the result is a simple vector.

这些答案确实有助于解释这一点,但对于非程序员(例如,像我这样第一次在数据科学课程背景下学习Python的人)来说,它仍然不是完全直观的。我仍然发现使用术语“沿着”或“每个”wrt的行和列是令人困惑的。

对我来说更有意义的是这样说:

轴0将作用于每个COLUMN中的所有row 轴1将作用于每个ROW中的所有COLUMNS

0轴上的均值是每列中所有行的均值,1轴上的均值是每行中所有列的均值。

从根本上说,这和@zhangxaochen和@Michael的意思是一样的,只是用一种更容易让我内化的方式。

数组被设计为坐标轴=0,行被垂直放置,而坐标轴=1,列被水平放置。Axis指的是数组的尺寸。

我认为还有另一种理解方式。

对于np。数组,如果我们想要消除列,我们使用axis = 1;如果我们想消除行,我们使用axis = 0。

np.mean(np.array(np.ones(shape=(3,5,10))),axis = 0).shape # (5,10)
np.mean(np.array(np.ones(shape=(3,5,10))),axis = 1).shape # (3,10)
np.mean(np.array(np.ones(shape=(3,5,10))),axis = (0,1)).shape # (10,)

对于pandas对象,axis = 0表示按行操作,axis = 1表示按列操作。这与numpy的定义不同,我们可以检查numpy.doc和pandas.doc的定义