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

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

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


当前回答

The easiest way for me to understand is to talk about whether you are calculating a statistic for each column (axis = 0) or each row (axis = 1). If you calculate a statistic, say a mean, with axis = 0 you will get that statistic for each column. So if each observation is a row and each variable is in a column, you would get the mean of each variable. If you set axis = 1 then you will calculate your statistic for each row. In our example, you would get the mean for each observation across all of your variables (perhaps you want the average of related measures).

轴= 0:按列=按列=沿行

轴= 1:按行=按行=沿列

其他回答

轴= 0表示从上到下 轴= 1表示从左到右

sums[key] = lang_sets[key].iloc[:,1:].sum(axis=0)

给定的例子是取column == key中所有数据的和。

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

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

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

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

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

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

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

我以前也很困惑,但我记得是这样的。

它指定将更改的数据帧的维度,或者将在其上执行操作。

让我们通过一个例子来理解这一点。 我们有一个数据框架df,它的形状是(5,10),这意味着它有5行10列。

现在,当我们使用df。mean(axis=1)时,它意味着维数1将被改变,这意味着它将有相同的行数,但不同的列数。因此得到的结果将是(5,1)的形状。

类似地,如果我们使用df.mean(axis=0),这意味着维度0将被改变,这意味着行数将被改变,但列数将保持不变,因此结果将是形状(1,10)。

试着把这个和问题中提供的例子联系起来。

轴在编程中是形状元组中的位置。这里有一个例子:

import numpy as np

a=np.arange(120).reshape(2,3,4,5)

a.shape
Out[3]: (2, 3, 4, 5)

np.sum(a,axis=0).shape
Out[4]: (3, 4, 5)

np.sum(a,axis=1).shape
Out[5]: (2, 4, 5)

np.sum(a,axis=2).shape
Out[6]: (2, 3, 5)

np.sum(a,axis=3).shape
Out[7]: (2, 3, 4)

轴上的均值将导致该维度被移除。

参考原题,dff形状为(1,2)。使用axis=1将形状更改为(1,)。