应该更广为人知的是,字符串别名 'index' 和 'columns' 可以用来代替整数 0/1。别名更加明确,帮助我记住计算是如何发生的。 'index' 的另一个别名是 'rows'。
当使用axis='index' 时,计算会沿列向下进行,这会造成混淆。但是,我记得它得到的结果与另一行的大小相同。
让我们在屏幕上获取一些数据,看看我在说什么:
df = pd.DataFrame(np.random.rand(10, 4), columns=list('abcd'))
a b c d
0 0.990730 0.567822 0.318174 0.122410
1 0.144962 0.718574 0.580569 0.582278
2 0.477151 0.907692 0.186276 0.342724
3 0.561043 0.122771 0.206819 0.904330
4 0.427413 0.186807 0.870504 0.878632
5 0.795392 0.658958 0.666026 0.262191
6 0.831404 0.011082 0.299811 0.906880
7 0.749729 0.564900 0.181627 0.211961
8 0.528308 0.394107 0.734904 0.961356
9 0.120508 0.656848 0.055749 0.290897
当我们想取所有列的平均值时,我们使用axis='index' 得到以下结果:
df.mean(axis='index')
a 0.562664
b 0.478956
c 0.410046
d 0.546366
dtype: float64
同样的结果会得到:
df.mean() # default is axis=0
df.mean(axis=0)
df.mean(axis='rows')
要在行上使用从左到右的操作,请使用axis='columns'。我记得可能会在我的 DataFrame 中添加一个额外的列:
df.mean(axis='columns')
0 0.499784
1 0.506596
2 0.478461
3 0.448741
4 0.590839
5 0.595642
6 0.512294
7 0.427054
8 0.654669
9 0.281000
dtype: float64
同样的结果会得到:
df.mean(axis=1)
添加一个axis=0/index/rows的新行
让我们使用这些结果添加额外的行或列来完成解释。因此,每当使用axis = 0/index/rows 时,就像获取DataFrame 的新行一样。让我们添加一行:
df.append(df.mean(axis='rows'), ignore_index=True)
a b c d
0 0.990730 0.567822 0.318174 0.122410
1 0.144962 0.718574 0.580569 0.582278
2 0.477151 0.907692 0.186276 0.342724
3 0.561043 0.122771 0.206819 0.904330
4 0.427413 0.186807 0.870504 0.878632
5 0.795392 0.658958 0.666026 0.262191
6 0.831404 0.011082 0.299811 0.906880
7 0.749729 0.564900 0.181627 0.211961
8 0.528308 0.394107 0.734904 0.961356
9 0.120508 0.656848 0.055749 0.290897
10 0.562664 0.478956 0.410046 0.546366
添加一个axis=1/columns的新列
同样,当axis=1/columns 时,它会创建可以轻松制作成自己的列的数据:
df.assign(e=df.mean(axis='columns'))
a b c d e
0 0.990730 0.567822 0.318174 0.122410 0.499784
1 0.144962 0.718574 0.580569 0.582278 0.506596
2 0.477151 0.907692 0.186276 0.342724 0.478461
3 0.561043 0.122771 0.206819 0.904330 0.448741
4 0.427413 0.186807 0.870504 0.878632 0.590839
5 0.795392 0.658958 0.666026 0.262191 0.595642
6 0.831404 0.011082 0.299811 0.906880 0.512294
7 0.749729 0.564900 0.181627 0.211961 0.427054
8 0.528308 0.394107 0.734904 0.961356 0.654669
9 0.120508 0.656848 0.055749 0.290897 0.281000
您似乎可以看到所有具有以下私有变量的别名:
df._AXIS_ALIASES
{'rows': 0}
df._AXIS_NUMBERS
{'columns': 1, 'index': 0}
df._AXIS_NAMES
{0: 'index', 1: 'columns'}