gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 15:47:45 24 4
gpt4 key购买 nike

给定以下 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

但是如何呢?

最佳答案

国际联合会

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

关于python - 按索引值连接 Pandas 多索引数据帧的行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48951492/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com