按索引值连接Pandas多索引数据帧的行

时间:2018-02-23 15:43:12

标签: python pandas dataframe

给出以下DataFrame,

              00:00:00 01:00:00 02:00:00
Date       ID                           
2018-01-01 A1       x1       x2       x3
           B3       y1       y2       y3
2018-01-02 A1       x4       x5       x6
           B3       y4       y5       y6
2018-03-02 A1       x7       x8       x9
           B3       y7       y8       y9

是用

获得的
import pandas as pd
idx = pd.MultiIndex.from_product([pd.to_datetime(["2018-01-01", "2018-01-02", "2018-03-02"]),
                                 ["A1", "B3"]], names=["Date", "ID"])
col = pd.timedelta_range("00:00:00", periods=3, freq="1H")
df = pd.DataFrame([["x1", "x2", "x3"], ["y1", "y2", "y3"], ["x4", "x5", "x6"],
                   ["y4", "y5", "y6"], ["x7", "x8", "x9"], ["y7", "y8", "y9"]], idx, col)

我想将其转换为以下形式,

datetime          A1   B3
2018-01-01 00:00  x1   y1
2018-01-01 01:00  x2   y2
2018-01-01 02:00  x3   y3
2018-01-02 00:00  x4   y4
2018-01-02 01:00  x5   y5
2018-01-02 02:00  x6   y6
2018-03-02 00:00  x7   y7
2018-03-02 01:00  x8   y8
2018-03-02 02:00  x9   y9

但是怎么样?

1 个答案:

答案 0 :(得分:3)

IIUC

df.unstack().swaplevel(axis=1).stack()
Out[1736]: 
ID                   A1  B3
Date                       
2018-01-01 00:00:00  x1  y1
           01:00:00  x2  y2
           02:00:00  x3  y3
2018-01-02 00:00:00  x4  y4
           01:00:00  x5  y5
           02:00:00  x6  y6
2018-03-02 00:00:00  x7  y7
           01:00:00  x8  y8
           02:00:00  x9  y9