pandas:按第一个索引的范围对MultiIndex进行切片,并选择二级索引标签

时间:2015-07-10 11:32:10

标签: python django pandas

我有一些按('dt', 'product_id')分组的销售数据,如下所示:

In [43]: sub.head()
Out[43]:
                           income
dt          product_id
2015-01-15  10016          23
2015-01-15  10017          188
2015-01-15  10018          NaN
2015-01-16  10016          188
2015-01-17  10025         1000
# this goes on and on...

如何在100162015-01-15之间查看产品2015-01-16的收入,我最好能够使用给定的MultiIndex切割这个庞大的数据帧,因为数据比较大。

1 个答案:

答案 0 :(得分:1)

.xs()是在多级索引中进行切片的好方法。 并.loc进一步提取所需的日期间隔。

import pandas as pd

# your df
# =======================
print(df)

Out[82]: 
                       income
dt         product_id        
2015-01-15 10016           23
           10017          188
           10018          NaN
2015-01-16 10016          188
2015-01-17 10025         1000

# one possible way
# ==========================================
df.xs(10016, level='product_id').loc['2015-01-15':'2015-01-16']

Out[88]: 
            income
dt                
2015-01-15      23
2015-01-16     188
相关问题