Drill Up/ Drill Down options

Hi Team,

I am exploring the option to drill up or drill down in a data frame. Is there any options to do so. Lets say from monthly I want to drill down to daily or something like that. Kindly help me out in this regard.


Hi Hari, this sounds like a good usecase for a pandas MultiIndex. You could, for example, store the level values of your dataframe’s MultiIndex in a user_selection = st.selectbox() widget and when the user selects a level of the index to drill down or up into, the dataframe could filter the results accordingly with df.loc[(user_selection)].

I can provide a code example if required.

Hi Cells would be really great if you can you help me by sharing a code example for the same.

Hari G

Sure thing, here you go. Let me know if this helps:

import pandas as pd
import streamlit as st

if __name__ == '__main__':

    # First, let's set up the multi index with 2 levels:
    # city and store. We will create an empty frame with some
    # column data (fruits) and pass in the multi index as index.
    # Index names are set for accessing later

    multi_index = pd.MultiIndex.from_product([
        ['city_1', 'city_2'],
        ['store_1', 'store_2', 'store_3'],
    df = pd.DataFrame(columns=['apples', 'oranges'], index=multi_index)
    df.index.set_names(['city', 'store'], inplace=True)

    # Now let's make some selectboxes for drilling up/down

    levels = [
        st.selectbox('Level 1', ['All'] + [i for i in df.index.get_level_values(0).unique()]),
        st.selectbox('Level 2', ['All'] + [i for i in df.index.get_level_values(1).unique()])

    # We need to use slice(None) if the user selects 'All'.
    # The specified level with 'All' will take all values in that level.

    for idx, level in enumerate(levels):
        if level == 'All':
            levels[idx] = slice(None)

    # Make a cross section with the level values and pass in the index names.

            (levels[0], levels[1]),
            level=['city', 'store']