我的数据框包含季度数据,对于某些公司,还包含月度数据。
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模型。
万分感谢!
发布于 2019-04-13 18:15:35
您只错过了排序,下面这行代码:
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 140https://stackoverflow.com/questions/55658276
复制相似问题