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

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=1,它将给出行和,keepdims=True将保持2D维度。 希望对你有所帮助。

其他回答

它指定了计算平均值的轴。默认情况下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  |
             ↓         ↓

我是这样理解的:

比如说,如果你的操作需要在数据框架中从左到右/从右到左,你显然是在合并列。你在不同的列上操作。 这是轴=1

例子

df = pd.DataFrame(np.arange(12).reshape(3,4),columns=['A', 'B', 'C', 'D'])
print(df)
   A  B   C   D
0  0  1   2   3
1  4  5   6   7
2  8  9  10  11 

df.mean(axis=1)

0    1.5
1    5.5
2    9.5
dtype: float64

df.drop(['A','B'],axis=1,inplace=True)

    C   D
0   2   3
1   6   7
2  10  11

这里需要注意的是,我们是在列上操作

类似地,如果您的操作需要在数据帧中从上到下/从下到上遍历,那么您正在合并行。轴为0。

比如说,如果你用df。然后你将得到一个元组,其中包含数据帧中的行数和列数作为输出。

In [10]: movies_df.shape
Out[10]: (1000, 11)

在上面的例子中,在movies数据帧中有1000行和11列,其中'row'在索引0位置中提到,'column'在索引1位置中提到。因此'axis=1'表示列,'axis=0'表示行。

学分:Github

熊猫的设计师韦斯•麦金尼(Wes McKinney)曾大量从事金融数据方面的工作。将列视为股票名称,将指数视为每日价格。然后,您可以猜测关于此财务数据的默认行为是什么(即,axis=0)。Axis =1可以简单地认为是“另一个方向”。

例如,诸如mean()、sum()、describe()、count()等统计函数都默认按列执行,因为对每只股票执行这些函数更有意义。Sort_index (by=)也默认为column。Fillna (method='ffill')将沿着列填充,因为它是相同的股票。Dropna()默认为row,因为您可能只是想丢弃当天的价格,而不是丢弃该股票的所有价格。

类似地,方括号索引指的是列,因为更常见的是选择股票而不是选择日期。

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

如果你对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.