如何使用Python中的Pandas从季度数据的行创建单列月度值?

问题描述 投票:4回答:1

我的数据框包含季度数据,也包含一些公司的月度数据。

import pandas as pd
df = pd.DataFrame({'quarter': ['2010-1', '2010-2', '2010-3','2010-4', '2011-1'],
                  'volume_quarter': [450, 450, 450, 450, 450],
                  'volume_month_1': [150, 150, 150, 150, 150],
                  'volume_month_2': [160, 160, 160, 160, 160],
                  'volume_month_3': [140, 140, 140, 140, 140]})
df

得到:

quarter volume_quarter  volume_month_1  volume_month_2  volume_month_3
2010-1  450               150            160               140
2010-2  450               150            160               140
2010-3  450               150            160               140
2010-4  450               150            160               140
2011-1  450               150            160               140

使用以下代码:

pd.melt(df, id_vars = ['quarter'], value_vars=['volume_month_1', "volume_month_2", "volume_month_3"])

我明白了:

    quarter variable    value
0   2010-1  volume_month_1  150
1   2010-2  volume_month_1  150
2   2010-3  volume_month_1  150
3   2010-4  volume_month_1  150
4   2011-1  volume_month_1  150
5   2010-1  volume_month_2  160
6   2010-2  volume_month_2  160
7   2010-3  volume_month_2  160
8   2010-4  volume_month_2  160
9   2011-1  volume_month_2  160
10  2010-1  volume_month_3  140
11  2010-2  volume_month_3  140
12  2010-3  volume_month_3  140
13  2010-4  volume_month_3  140
14  2011-1  volume_month_3  140

相反,我试图实现以下目标:


    quarter variable        value
0   2010-1  volume_month_1  150
1   2010-1  volume_month_2  160
2   2010-1  volume_month_3  140
3   2010-2  volume_month_1  150
4   2010-2  volume_month_2  160
5   2010-2  volume_month_3  140
6   2010-3  volume_month_1  150
7   2010-3  volume_month_2  160
8   2010-3  volume_month_3  140
9   2010-4  volume_month_1  150
10  2010-4  volume_month_2  160
11  2010-4  volume_month_3  140
12  2011-1  volume_month_1  150
13  2011-1  volume_month_2  160
14  2011-1  volume_month_3  140

我想实现这个目标,所以我可以在montly值上运行Arima模型。

百万提前谢谢!

python pandas pivot-table melt
1个回答
1
投票

你只错过了排序,这行代码:

df = (
    pd.melt(
        df,
        id_vars=["quarter"],
        value_vars=["volume_month_1", "volume_month_2", "volume_month_3"],
    )
    .sort_values(by="quarter")
    .reset_index(drop=True)
)

根据需要返回:

   quarter        variable  value
0   2010-1  volume_month_1    150
1   2010-1  volume_month_2    160
2   2010-1  volume_month_3    140
3   2010-2  volume_month_1    150
4   2010-2  volume_month_2    160
5   2010-2  volume_month_3    140
6   2010-3  volume_month_1    150
7   2010-3  volume_month_2    160
8   2010-3  volume_month_3    140
9   2010-4  volume_month_1    150
10  2010-4  volume_month_2    160
11  2010-4  volume_month_3    140
12  2011-1  volume_month_1    150
13  2011-1  volume_month_2    160
14  2011-1  volume_month_3    140
© www.soinside.com 2019 - 2024. All rights reserved.