将所有数据框列连接到一个列中

时间:2019-05-22 17:13:27

标签: python pandas datetime time-series concatenation

我有一个大致像这样的数据框:

        01/01/19 02/01/19 03/01/19 04/01/19
hour                                                                           
1.0     27.08    47.73    54.24    10.0 
2.0     26.06    49.53    46.09    22.0
...
24.0    12.0     34.0     22.0     40.0

我想使用适当的日期索引将所有列连接在一起,以将其尺寸减小为一列。有没有做到这一点的聪明方法?

预期结果...类似

01/01/19 00:00:00   27.08
01/01/19 01:00:00   26.08
...
01/01/19 23:00:00   12.00
02/01/19 00:00:00   47.73
02/01/19 01:00:00   49.53
...
02/01/19 23:00:00   34.00
...

1 个答案:

答案 0 :(得分:6)

您可以使用pd.to_datetimepd.to_timedelta堆叠然后固定索引:

u = df.stack()  
u.index = (pd.to_datetime(u.index.get_level_values(1), dayfirst=True) 
         + pd.to_timedelta(u.index.get_level_values(0) - 1, unit='h'))

u.sort_index()

2019-01-01 00:00:00    27.08
2019-01-01 01:00:00    26.06
2019-01-01 23:00:00    12.00
2019-01-02 00:00:00    47.73
2019-01-02 01:00:00    49.53
2019-01-02 23:00:00    34.00
2019-01-03 00:00:00    54.24
2019-01-03 01:00:00    46.09
2019-01-03 23:00:00    22.00
2019-01-04 00:00:00    10.00
2019-01-04 01:00:00    22.00
2019-01-04 23:00:00    40.00
dtype: float64