[Python] Apply float styling to specific rows in pandas dataframe

Discussão em 'Python' iniciado por Stack, Abril 26, 2025.

  1. Stack

    Stack Membro Participativo

    I've created a large dataframe with a smaller dataframe that represents a summary of some calculations run on the larger dataframe. This will find certain percentages, max/min of some columns, etc. I'd like it to look like this:

    Index Value
    Remaining % 1.7%
    Largest Stock AAPL
    Total Days 3

    As you can see there are a mix of numbers and strings - some I'd like to represent as ints, others as float %s, etc.

    I'd like to be able to select certain rows to adjust the precision, select others and add a "%" sign, and leave some alone.

    I have been able to use stylers to style dataframes previously, but they seem only able to select columns and not rows:

    summary_tile
    .style
    .set_table_styles(styles)
    .format({
    'Remaining %:': '{:.2f}%'})


    This informs me that 'Remaining %' is not a column.

    I've tried similar things:

    summary_tile
    .style
    .set_table_styles(styles))
    .applymap(
    lambda x: '{:.2f}%'.format(x),
    subset=pd.IndexSlice['Remaining %:', :])


    I've also tried passing a function to apply map:

    def percent_style(x):
    return '{:.2f}%'.format(x)

    summary_tile
    .style
    .set_table_styles(styles)
    .apply(percent_style, axis=1, subset=(pd.IndexSlice['Remaining %:', :])


    Neither of these work. Is there a way to pass this kind of formatting to rows only? I am also open to representing my summary table differently, perhaps there is a better way to lay it out that would be easier to style or more readable.

    Continue reading...

Compartilhe esta Página