Search code examples
pandaspanel

Add column to Interactive pd.DataFrame


I'm having trouble to understand how to deal with pandas DataFrame once it is interactive. Also I can't find any helpful sources to find out what options an interactive DataFrame is providing.

Currently I am stuck trying to add a column to an interactive Dataframe.

import pandas as pd
import hvplot.pandas
import holoviews as hv
import panel as pn

dictionary = {'A':[12,13,14,15],
              'B':[17,18,19,20],
              'C':[35,36,37,38],
              'D':[45,46,47,48]}

index = pd.to_datetime(['2017-06-08', '2017-06-09', '2017-06-10', '2017-06-11'])

df = pd.DataFrame(dictionary, index=index)

dfi = df.interactive()

I added a panel-Date slider to play around with the DataFrame:

date_slider = pn.widgets.DateRangeSlider(name='Date',start=df.index.min(),end=df.index.max())

slider_df = dfi[
        (dfi.index >= date_slider.param.value_start) &
        (dfi.index <= date_slider.param.value_end)].sum()

The output I want to discuss looks like this: Interactive DataFrame with Date-Slider

I have the sum of all selected values in an extra column.

How can I rename the column to "sum"? How can I add another column for .mean()?


Solution

  • There are two ways to do this:

    slider_df = dfi[
            (dfi.index >= date_slider.param.value_start) &
            (dfi.index <= date_slider.param.value_end)].agg(['sum','mean'])
    

    which will result in

    enter image description here

    or

    slider_df = dfi[
            (dfi.index >= date_slider.param.value_start) &
            (dfi.index <= date_slider.param.value_end)].agg(['sum','mean']).T
    

    which gives

    enter image description here