下面是我生成一个数据框架的代码:
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
我的问题是:轴在熊猫中是什么意思?
轴在编程中是形状元组中的位置。这里有一个例子:
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,)。
我认为还有另一种理解方式。
对于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的定义