Dev1243
Dev1243

Reputation: 1

Formatting specific rows in Dash Datatable with %, $, etc

I am using the Dash Datatable code to create the table in Plotly/Python. I would like to format the various rows in value column. For example, I would like to format Row[1] with $ sign, while Row[2] with %. TIA

#Row  KPI   Value  
0      AA    1  
1      BB    $230.  
2      CC    54%  
3      DD    5.6.  
4      EE    $54000   

Table

Upvotes: 0

Views: 1697

Answers (1)

timovp
timovp

Reputation: 41

I have been looking into this issue as well. unfortunately I didn't succeed with any thing built-in either. If you do in the future, please let me know. However, the solution that I implemented was the following function to easily change the format of DataFrame elements to strings with the formatting I would like:

def dt_formatter(df:pd.DataFrame, 
                 formatter:str, 
                 slicer:pd.IndexSlice=None)->pd.DataFrame:
    if not slicer:
        for col in df.columns:
            df[col] = df[col].apply(formatter.format,axis = 0)
        return df
    else: 
        dfs = df.loc[slicer].copy()
        for col in dfs.columns:
            dfs[col] = dfs[col].apply(formatter.format,axis = 0)
        df.loc[slicer] = dfs
        return df

and the using your regular slicing / filtering with your base dataframe df. Assuming your base df looks like this:

>>> df
#Row  KPI   Value  
0      AA    1  
1      BB    230  
2      CC    54  
3      DD    5.6  
4      EE    54000   

>>> df = dt_formatter(df, '{:.0%}', pd.IndexSlice[df['#Row'] == 1,'Value')
>>> df
    #Row  KPI   Value  
0      AA    1  
1      BB    230%  
2      CC    54  
3      DD    5.6  
4      EE    54000 

using a different slicer and different formatting string, you could "build" your DataFrame using such a helper function.

Upvotes: 1

Related Questions