gpt4 book ai didi

python - 多索引第二级的时间片

转载 作者:行者123 更新时间:2023-12-04 18:32:24 25 4
gpt4 key购买 nike

pandas 允许对时间索引进行很酷的切片。例如,我可以切片数据帧 df从 2012 年 1 月到 2012 年 3 月,执行以下操作:

df['2012-01':'2012-03']

但是,我有一个数据框 df具有多索引,其中时间索引是第二级。看起来像:
                     A         B         C         D         E
a 2001-01-31 0.864841 0.789273 0.370031 0.448256 0.178515
2001-02-28 0.991861 0.079215 0.900788 0.666178 0.693887
2001-03-31 0.016674 0.855109 0.984115 0.436574 0.480339
2001-04-30 0.120924 0.046013 0.659807 0.210534 0.694029
2001-05-31 0.788149 0.296244 0.478201 0.845042 0.437814
b 2001-01-31 0.497646 0.349958 0.223227 0.812331 0.975012
2001-02-28 0.542572 0.472267 0.276186 0.970909 0.138683
2001-03-31 0.960813 0.666942 0.069349 0.282741 0.127992
2001-04-30 0.491422 0.678742 0.048784 0.612312 0.713472
2001-05-31 0.718721 0.504403 0.069047 0.253682 0.836386

我仍然可以通过以下方式在任何特定级别使用上述方法进行切片:
df.loc['a']['2012-01':'2012-03']

但这仅适用于 level0 == 'a' .

如何对 level0 中的所有值执行此操作?我期待这样的事情:
                     A         B         C         D         E
a 2001-01-31 0.864841 0.789273 0.370031 0.448256 0.178515
2001-02-28 0.991861 0.079215 0.900788 0.666178 0.693887
2001-03-31 0.016674 0.855109 0.984115 0.436574 0.480339
b 2001-01-31 0.497646 0.349958 0.223227 0.812331 0.975012
2001-02-28 0.542572 0.472267 0.276186 0.970909 0.138683
2001-03-31 0.960813 0.666942 0.069349 0.282741 0.127992

最佳答案

使用 pd.IndexSlice

df.loc[pd.IndexSlice[:, '2001-01':'2001-3'], :]

enter image description here

关于python - 多索引第二级的时间片,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38346668/

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