当我用一个变量旋转面板数据集并将月放在 Y 轴上,年放在 X 轴上时,Python 执行什么操作?

What operation does Python perform when I pivot a panel dataset with one variable and put month on the Y-axis and years on the X-axis?

我有一个名为 panel_df 面板数据集 ,其中包含以下列:idyearmonth 和一个变量 x

然后我通过以下行:

panel_df.pivot_table(values=x, index='month', columns='year')

我获得的输出是一个 table,y 轴为 month,x 轴为 year,因此每个单元格都是一个由 year-month对.

我的疑惑是:Python在执行上面这行代码的时候做了什么?是否取横截面的平均值,即对于每个 year-month 对取所有 idx 的平均值?

提前感谢大家的宝贵时间。

对于python版本0.23.4,默认对应参数aggfunc设置为'mean':
https://pandas.pydata.org/pandas-docs/version/0.23.4/generated/pandas.DataFrame.pivot_table.html
因此,对于每个年月对,pivot 取所有相应 observations.

的平均值 x
>>> import pandas as pd
>>> panel_df = \
pd.DataFrame(
    {
        'id':[0]*8 + [1]*8,
        'year':[2010]*4 + [2011]*4 + [2010]*4 + [2011]*4,
        'month':[1,1,7,7]*4,
        'x':[i for i in range(16)],
    }
)
>>> panel_df

    id  year  month   x
0    0  2010      1   0
1    0  2010      1   1
2    0  2010      7   2
3    0  2010      7   3
4    0  2011      1   4
5    0  2011      1   5
6    0  2011      7   6
7    0  2011      7   7
8    1  2010      1   8
9    1  2010      1   9
10   1  2010      7  10
11   1  2010      7  11
12   1  2011      1  12
13   1  2011      1  13
14   1  2011      7  14
15   1  2011      7  15

然后:

>>> panel_df.pivot_table(
    values = 'x',
    index = 'month',
    columns = 'year'
)
year   2010  2011
month            
1       4.5   8.5
7       6.5  10.5

相当于:

>>> panel_df.pivot_table(
    values = 'x',
    index = 'month',
    columns = 'year',
    aggfunc='mean',
    fill_value=None,
    margins=False
)
year   2010  2011
month            
1       4.5   8.5
7       6.5  10.5

您可以将参数 aggfunc 的默认值更改为 'sum' 例如:

>>> panel_df.pivot_table(
    values = 'x',
    index = 'month',
    columns = 'year',
    aggfunc='sum',
    fill_value=None,
    margins=False
)
year   2010  2011
month            
1        18    34
7        26    42

您可能还会发现使用 margins 值并将其设置为 True 很有用:

>>> panel_df.pivot_table(
    values = 'x',
    index = 'month',
    columns = 'year',
    aggfunc='sum',
    fill_value=None,
    margins=True
)

year   2010  2011  All
month                 
1        18    34   52
7        26    42   68
All      44    76  120