本文介绍了第二级多索引上的时间片的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
pandas可以对时间索引进行切片.例如,通过执行以下操作,我可以对从2012年1月到2012年3月的月份中的数据帧df
进行切片:
pandas allows for cool slicing on time indexes. For example, I can slice a dataframe df
for the months from Janurary 2012 to March 2012 by doing:
df['2012-01':'2012-03']
但是,我有一个带有多重索引的数据帧df
,其中时间索引是第二级.看起来像:
However, I have a dataframe df
with a multiindex where the time index is the second level. It looks like:
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
我仍然可以在任何特定级别使用上述方法进行切片:
I can still slice using the method above on any specific level by:
df.loc['a']['2012-01':'2012-03']
但这仅用于level0 == 'a'
.
如何对level0
中的所有值执行此操作?我期望这样的事情:
How do I do this for all values in level0
? I expect something like this:
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'], :]
这篇关于第二级多索引上的时间片的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!