下面是我生成一个数据框架的代码:
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
我的问题是:轴在熊猫中是什么意思?
这里的许多答案对我帮助很大!
如果你对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.
我认为还有另一种理解方式。
对于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的定义