下面是我生成一个数据框架的代码:
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
我的问题是:轴在熊猫中是什么意思?
我是这样理解的:
比如说,如果你的操作需要在数据框架中从左到右/从右到左,你显然是在合并列。你在不同的列上操作。
这是轴=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。
轴在编程中是形状元组中的位置。这里有一个例子:
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,)。