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

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

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


当前回答

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

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

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

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

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

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

其他回答

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,列被水平放置。Axis指的是数组的尺寸。

它指定了计算平均值的轴。默认情况下axis=0。这与numpy一致。显式指定axis时的平均使用量(在numpy中)。mean, axis==None,默认情况下,它计算扁平数组上的平均值),其中,沿行轴=0(即,以pandas为单位的索引),沿列轴=1。为了增加清晰度,可以选择指定axis='index'(而不是axis=0)或axis='columns'(而不是axis=1)。

+------------+---------+--------+
|            |  A      |  B     |
+------------+---------+---------
|      0     | 0.626386| 1.52325|----axis=1----->
+------------+---------+--------+
             |         |
             | axis=0  |
             ↓         ↓

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

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

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

实际上我们不需要记住轴=0轴=1代表什么。 有时,axis可以是一个元组:例如axis=(0,1)我们如何理解这样多个dim轴?

我发现如果我们理解python slice[:]是如何工作的,就会更容易。

假设我们有一个一维数组: A = [0,1,0]

a[:] # select all the elements in array a

假设我们有一个2d数组:

M = [[0, 0, 1],
     [1, 0, 0],
     [0, 2, 1],
     [2, 0, 2],
     [3, 1, 0]]
M[1,:] # M[0]=1, M[1]=* --> [1, 0, 0]
M[:,2] # M[0]=*, M[1]=2 --> [1, 0, 1, 2, 0]
M[:,:] # M[0]=*, M[1]=* --> all the elements in M are selected

当计算时:

np.sum(M, axis=0) # [sum(M[:,0]), sum(M[:,1]), sum(M[:,2])]
np.sum(M, axis=1) # [sum(M[0,:]), sum(M[1,:]), sum(M[2,:]), sum(M[3,:]), sum(M[4,:])]
np.sum(M, axis=-1) # -1 means last dim, it's the same with np.sum(M, axis=1)
np.sum(M, axis=(0,1)) # sum(M[:,:])

规则很简单,当计算时将axis中指定的暗值替换为:。