我有pandas数据帧,我想在每4列之后切片,然后垂直堆叠在彼此之上,其中包括日期作为索引。这是否可以通过使用np.vstack()?提前谢谢!
请参考图像以获取数据帧。 我想要这样的东西
答案 0 :(得分:0)
Until you provide a Minimal, Complete, and Verifiable example, I will not test this answer but the following should work:
given that we have the data stored in a Pandas DataFrame
called df
, we can use pd.melt
moltendfs = []
for i in range(4):
moltendfs.append(df.iloc[:, i::4].reset_index().melt(id_vars='date'))
newdf = pd.concat(moltendfs, axis=1)
We use iloc
to take only every fourth column, starting with the i-th column. Then we reset_index
in order to be able to keep the date column as our identifier variable. We use melt
in order to melt our DataFrame. Finally we simply concatenate all of these molten DataFrames together side by side.