【发布时间】:2021-11-11 14:58:12
【问题描述】:
我正在处理预测数据。
我想从当前列名创建一个新列 (horizon),并将两个变量 (["y", "yhat"]) 中的值堆叠起来
import pandas as pd
import numpy as np
import itertools
rng = np.random.default_rng(2021)
index = list(itertools.product(
["pixel_1", "pixel_2"],
pd.date_range("2001-01-01", "2002-01-01", freq="D")
))
dat = pd.DataFrame({
"initialisation_time": np.array(index)[:, 1],
"pixel": np.array(index)[:, 0],
"y_0": rng.random(len(index)),
"y_1": rng.random(len(index)),
"yhat_0": rng.random(len(index)),
"yhat_1": rng.random(len(index)),
})
给我一个如下的数据框:
time pixel y_0 y_1 yhat_0 yhat_1
0 2001-01-01 pixel_1 0.257135 0.609062 0.989102 0.297949
1 2001-01-02 pixel_1 0.898808 0.509193 0.966388 0.182610
2 2001-01-03 pixel_1 0.724221 0.537482 0.455078 0.141172
3 2001-01-04 pixel_1 0.503014 0.391576 0.382041 0.652105
4 2001-01-05 pixel_1 0.688625 0.865679 0.828888 0.856478
.. ... ... ... ... ... ...
727 2001-12-28 pixel_2 0.697661 0.725550 0.926735 0.527801
728 2001-12-29 pixel_2 0.052295 0.632843 0.536919 0.817767
729 2001-12-30 pixel_2 0.306129 0.426934 0.638589 0.697375
730 2001-12-31 pixel_2 0.633789 0.982248 0.255824 0.982358
731 2002-01-01 pixel_2 0.922154 0.088203 0.887233 0.700154
[732 rows x 6 columns]
## 我想要一个格式如下的数据框:
将四列 (["y_0", "y_1", "yhat_0", "yhat_1"]) 转换为三列 (["horizon", "y", "yhat"])。
target_lookalike = pd.DataFrame({
"initialisation_time": np.tile(np.array(index)[:, 1], 2),
"pixel": np.tile(np.array(index)[:, 0], 2),
"horizon": np.tile([0, 1], len(index)),
"y": rng.random(len(index) * 2),
"y_hat": rng.random(len(index) * 2),
})
initialisation_time pixel horizon y y_hat
0 2001-01-01 pixel_1 0 0.833400 0.457637
1 2001-01-02 pixel_1 1 0.607682 0.302057
2 2001-01-03 pixel_1 0 0.474058 0.045079
3 2001-01-04 pixel_1 1 0.198236 0.586153
4 2001-01-05 pixel_1 0 0.047407 0.179364
... ... ... ... ... ...
1459 2001-12-28 pixel_2 1 0.157809 0.997542
1460 2001-12-29 pixel_2 0 0.659860 0.830327
1461 2001-12-30 pixel_2 1 0.047798 0.541301
1462 2001-12-31 pixel_2 0 0.002146 0.945190
1463 2002-01-01 pixel_2 1 0.636621 0.735699
[1464 rows x 5 columns]
地平线取自列字符串("y_0" 将是 horizon == 0),值分配给 y 或 y_hat。
【问题讨论】:
-
在您的预期输出中,initialisation_time 列不应该在每个日期都有两个条目吗?
标签: python pandas dataframe forecasting