gpt4 book ai didi

python - 将 pandas 多索引折叠为单个索引

转载 作者:太空狗 更新时间:2023-10-30 00:47:36 25 4
gpt4 key购买 nike

我有一个多索引的 Pandas 数据框,如下所示:

enter image description here

如何将三级索引合并为一个索引?即,我想将 (1987, 1, 2) 变成 pd.datetime(1987, 1, 2)。我更喜欢使用 df.index.map 的矢量化方法。这是可以创建数据框顶部的代码:

df = pd.DataFrame(
{'3 months': [1, 2, 3, 4, 5]},
index=[
[1987, 1987, 1987, 1987,1987],
[1,1,1,1,1],
[2,5,6,7,8]
]
)

最佳答案

使用pd.Index.map 的最简单的解决方案

df.set_index(df.index.map(lambda t: pd.datetime(*t)))

3 months
1987-01-02 1
1987-01-05 2
1987-01-06 3
1987-01-07 4
1987-01-08 5

关于python - 将 pandas 多索引折叠为单个索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48431868/

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