我有以下格式的日内股票数据。
09:30:00 09:31:00 09:32:00 09:33:00 09:34:00 09:35:00
2011-01-01 -0.358525 -0.185970 -0.357479 -1.486157 -1.101909 -1.957380
2011-01-02 -0.489747 -0.341163 1.588071 -0.146610 -0.185834 -0.872918
2011-01-03 0.682824 -0.344875 -0.641186 -0.501414 0.877347 2.183530
我想将其转换为时间序列数据,如下所示。
2011-01-01 09:30:00 -0.358525
2011-01-01 09:31:00 -0.185970
2011-01-01 09:32:00 -0.357479
2011-01-01 09:33:00 -1.486157
2011-01-01 09:34:00 -1.101909
2011-01-01 09:35:00 -1.957380
2011-01-02 09:30:00 -0.489747
2011-01-02 09:31:00 -0.341163
2011-01-02 09:32:00 1.588071
2011-01-02 09:33:00 -0.146610
2011-01-02 09:34:00 -0.185834
2011-01-02 09:35:00 -0.872918
2011-01-03 09:30:00 0.682824
2011-01-03 09:31:00 -0.344875
2011-01-03 09:32:00 -0.641186
2011-01-03 09:33:00 -0.501414
2011-01-03 09:34:00 0.877347
2011-01-03 09:35:00 2.183530
我尝试了很少的熊猫功能,但没有成功。我是python的新手,任何帮助或提示赞赏。
答案 0 :(得分:4)
您可以使用stack
方法:
In [130]: s = df.stack()
In [131]: s
Out[131]:
2011-01-01 09:30:00 -0.358525
09:31:00 -0.185970
09:32:00 -0.357479
09:33:00 -1.486157
09:34:00 -1.101909
09:35:00 -1.957380
2011-01-02 09:30:00 -0.489747
09:31:00 -0.341163
09:32:00 1.588071
09:33:00 -0.146610
09:34:00 -0.185834
09:35:00 -0.872918
2011-01-03 09:30:00 0.682824
09:31:00 -0.344875
09:32:00 -0.641186
09:33:00 -0.501414
09:34:00 0.877347
09:35:00 2.183530
dtype: float64
这会创建一个具有多索引的系列(具有两个级别的索引)。要将两个级别合并到一个索引中,您可以这样做(对于每个索引条目,我只是将两个级别连接起来,并且两者之间有空格):
In [132]: s.index = [" ".join([l1, l2]) for l1, l2 in s.index]
In [133]: s
Out[133]:
2011-01-01 09:30:00 -0.358525
2011-01-01 09:31:00 -0.185970
2011-01-01 09:32:00 -0.357479
2011-01-01 09:33:00 -1.486157
2011-01-01 09:34:00 -1.101909
2011-01-01 09:35:00 -1.957380
2011-01-02 09:30:00 -0.489747
2011-01-02 09:31:00 -0.341163
2011-01-02 09:32:00 1.588071
2011-01-02 09:33:00 -0.146610
2011-01-02 09:34:00 -0.185834
2011-01-02 09:35:00 -0.872918
2011-01-03 09:30:00 0.682824
2011-01-03 09:31:00 -0.344875
2011-01-03 09:32:00 -0.641186
2011-01-03 09:33:00 -0.501414
2011-01-03 09:34:00 0.877347
2011-01-03 09:35:00 2.183530
dtype: float64
假设您从字符串索引和列标签开始,现在可以将字符串索引转换为实际的DatetimeIndex:
In [135]: s.index = pd.DatetimeIndex(s.index)