将多列转换为MultiIndex

时间:2018-08-28 17:20:46

标签: python python-3.x pandas

我使用的库返回一个DataFrame进行分析。此DataFrame是具有多个列的简单时间序列。我想将其中的几列连接到MultiIndex并将结果导出为JSON文件。

示例:

In[2]: df.loc[:, ['open', 'high', 'low', 'close']].tail()
Out[2]: 
                               open      high       low     close
period_close                                                     
2018-08-20 23:56:00+00:00  0.001837  0.001837  0.001837  0.001837
2018-08-20 23:57:00+00:00  0.001837  0.001837  0.001837  0.001837
2018-08-20 23:58:00+00:00  0.001837  0.001841  0.001830  0.001841
2018-08-20 23:59:00+00:00  0.001827  0.001840  0.001814  0.001832
2018-08-21 00:00:00+00:00  0.001824  0.001831  0.001824  0.001831

我想将此表格转换为以下格式:

                                                             candle
period_close                                                     
2018-08-20 23:56:00+00:00  [0.001837, 0.001837, 0.001837, 0.001837]
2018-08-20 23:57:00+00:00  [0.001837, 0.001837, 0.001837, 0.001837]
2018-08-20 23:58:00+00:00  [0.001837, 0.001841, 0.001830, 0.001841]
2018-08-20 23:59:00+00:00  [0.001827, 0.001840, 0.001814, 0.001832]
2018-08-21 00:00:00+00:00  [0.001824, 0.001831, 0.001824, 0.001831]

1 个答案:

答案 0 :(得分:2)

您可以重新创建数据框

Newdf=pd.DataFrame({'candle':df.values.tolist()},index=df.index)
Newdf
Out[221]: 
                                                                     candle
period_close                                                               
2018-08-2023:56:00+00:00           [0.001837, 0.001837, 0.001837, 0.001837]
2018-08-2023:57:00+00:00           [0.001837, 0.001837, 0.001837, 0.001837]
2018-08-2023:58:00+00:00            [0.001837, 0.001841, 0.00183, 0.001841]
2018-08-2023:59:00+00:00  [0.001827, 0.0018399999999999998, 0.001814, 0....
2018-08-2100:00:00+00:00  [0.0018239999999999999, 0.001831, 0.0018239999...