我需要将 DataFrame reshape 为以下形状:
sample_df
Out[97]:
0 1 2 3
0 2011-01-01 00:00:00 123.39 2012-01-01 00:00:00 123.4
1 2011-01-01 01:00:00 123.39 2012-01-01 01:00:00 123.38
2 2011-01-01 02:00:00 123.4 2012-01-01 02:00:00 123.4
3 2011-01-01 03:00:00 123.4 2012-01-01 03:00:00 123.4
4 2011-01-01 04:00:00 123.41 2012-01-01 04:00:00 123.4
变成以下形状:
reshaped_sample_df
Out[97]:
0 1
0 2011-01-01 00:00:00 123.39
1 2011-01-01 01:00:00 123.39
2 2011-01-01 02:00:00 123.4
3 2011-01-01 03:00:00 123.4
4 2011-01-01 04:00:00 123.41
5 2012-01-01 00:00:00 123.4
6 2012-01-01 01:00:00 123.38
7 2012-01-01 02:00:00 123.4
8 2012-01-01 03:00:00 123.4
9 2012-01-01 04:00:00 123.4
我一直在努力研究 Pandas 中的大量 reshape 数据函数,但没有成功。
最佳答案
假设您以 2 步进行 reshape ,您可以转储到 numpy 并重建数据帧:
pd.DataFrame(np.reshape(df.to_numpy(), (-1,2)))
0 1
0 2011-01-01 00:00:00 123.39
1 2012-01-01 00:00:00 123.4
2 2011-01-01 01:00:00 123.39
3 2012-01-01 01:00:00 123.38
4 2011-01-01 02:00:00 123.4
5 2012-01-01 02:00:00 123.4
6 2011-01-01 03:00:00 123.4
7 2012-01-01 03:00:00 123.4
8 2011-01-01 04:00:00 123.41
9 2012-01-01 04:00:00 123.4
关于python - reshape DataFrame 列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72656503/