python - reshape DataFrame 列

标签 python pandas dataframe

我需要将 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/

相关文章:

python - 使用不同命令时重复相同的短语

python - Pandas:合并数据帧并将多个连接值合并到一个数组中

python - 从元组列表创建 pandas 日期时间索引

python - 在 python 中理解的字典列表

python - Beautiful Soup 无法从表中获取信息

python - 使用 bool 语句处理 Pandas 系列

python - Pandas Lookup 将被弃用——优雅高效的替代方案

python - 基于对多列 pandas python 的逻辑操作更新另一列

python - 在 Python 中获取组之间的累积平均值

python - 在 pandas groupby 中删除具有特定值的组开头的行