下面是我生成一个数据框架的代码:
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=的问题在于它在两种主要不同情况下的使用:
用于计算累积值或重新排列(如排序)数据。
用于操纵(“玩”)实体(例如数据帧)。
这个答案背后的主要思想是为了避免混淆,我们选择一个数字或一个名称来指定特定的轴,以更清楚、直观和描述性的为准。
Pandas基于NumPy, NumPy基于数学,特别是n维矩阵。下面是三维空间中数学中常用的轴的名称:
这张图仅用于记忆坐标轴的序数:
x轴为0,
y轴为1,和
z轴为2。
z轴仅用于面板;对于数据框架,我们将把我们的兴趣限制在带有x轴(0,垂直)和y轴(1,水平)的绿色二维基本平面上。
这都是关于axis= parameter的潜在值的数字。
轴的名称是“索引”(你可以使用别名“行”)和“列”,为了解释这些名称和(轴的)序数之间的关系并不重要,因为每个人都知道“行”和“列”是什么意思(这里的每个人-我想-都知道“索引”在pandas中的意思)。
现在,我的建议是
If you want to compute an accumulated value, you may compute it from values located along axis 0 (or along axis 1) — use axis=0 (or axis=1).
Similarly, if you want to rearrange values, use the axis number of the axis, along which are located data for rearranging (e.g. for sorting).
If you want to manipulate (e.g. concatenate) entities (e.g. dataframes) — use axis='index' (synonym: axis='rows') or axis='columns' to specify the resulting change — index (rows) or columns, respectively.
(For concatenating, you will obtain either a longer index (= more rows), or more columns, respectively.)