下面是我生成一个数据框架的代码:

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

我的问题是:轴在熊猫中是什么意思?


当前回答

轴= 0表示从上到下 轴= 1表示从左到右

sums[key] = lang_sets[key].iloc[:,1:].sum(axis=0)

给定的例子是取column == key中所有数据的和。

其他回答

它指定了计算平均值的轴。默认情况下axis=0。这与numpy一致。显式指定axis时的平均使用量(在numpy中)。mean, axis==None,默认情况下,它计算扁平数组上的平均值),其中,沿行轴=0(即,以pandas为单位的索引),沿列轴=1。为了增加清晰度,可以选择指定axis='index'(而不是axis=0)或axis='columns'(而不是axis=1)。

+------------+---------+--------+
|            |  A      |  B     |
+------------+---------+---------
|      0     | 0.626386| 1.52325|----axis=1----->
+------------+---------+--------+
             |         |
             | axis=0  |
             ↓         ↓

数组被设计为坐标轴=0,行被垂直放置,而坐标轴=1,列被水平放置。Axis指的是数组的尺寸。

熊猫的设计师韦斯•麦金尼(Wes McKinney)曾大量从事金融数据方面的工作。将列视为股票名称,将指数视为每日价格。然后,您可以猜测关于此财务数据的默认行为是什么(即,axis=0)。Axis =1可以简单地认为是“另一个方向”。

例如,诸如mean()、sum()、describe()、count()等统计函数都默认按列执行,因为对每只股票执行这些函数更有意义。Sort_index (by=)也默认为column。Fillna (method='ffill')将沿着列填充,因为它是相同的股票。Dropna()默认为row,因为您可能只是想丢弃当天的价格,而不是丢弃该股票的所有价格。

类似地,方括号索引指的是列,因为更常见的是选择股票而不是选择日期。

我的想法是:Axis = n,其中n = 0,1等意味着矩阵沿该轴折叠(折叠)。所以在一个二维矩阵中,当你沿着0(行)折叠时,你实际上是一次对一列进行操作。对于高阶矩阵也是如此。

这与对矩阵中维数的正常引用不同,其中0 ->行和1 ->列。对于N维数组中的其他维度也是如此。

The easiest way for me to understand is to talk about whether you are calculating a statistic for each column (axis = 0) or each row (axis = 1). If you calculate a statistic, say a mean, with axis = 0 you will get that statistic for each column. So if each observation is a row and each variable is in a column, you would get the mean of each variable. If you set axis = 1 then you will calculate your statistic for each row. In our example, you would get the mean for each observation across all of your variables (perhaps you want the average of related measures).

轴= 0:按列=按列=沿行

轴= 1:按行=按行=沿列