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

2024-04-26 18:56:58 发布

您现在位置:Python中文网/ 问答频道 /正文

我的数据框架包含季度数据和一些公司的月度数据。你知道吗

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模型。你知道吗

万分感谢!你知道吗


Tags: 数据import框架pandasdfvalue公司vars
1条回答
网友
1楼 · 发布于 2024-04-26 18:56:58

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

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

相关问题 更多 >