[Fixed]-Pandas: slice on MultiIndex by range of first index, and choose secondary index label

1๐Ÿ‘

โœ…

.xs() is a good way to do slicing in multi-level index.
And .loc to further extract the required date intervals you want.

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
๐Ÿ‘คJianxun Li

Leave a comment