Home > Blockchain >  Formatting column in pandas to decimal places using table.style based on value
Formatting column in pandas to decimal places using table.style based on value

Time:01-29

I am trying to format a column in a dataframe using style. So far I successfully used the styling for a fixed number of decimals:

mytable.style.format('{:,.2f}', pd.IndexSlice[:, ['Price']])

but I need to expand this to formatting based on value as this:

  • if value is >=1000, then format to zero decimal places
  • if value is between 1000 and 1, then format to two decimal places
  • if value is < 1, then format to five decimal places

Does anyone have a solution for this? Thank you!

CodePudding user response:

What you are looking for is called "conditional formatting". In which you set the conditions like you described and return the right format. There are examples in the documentation, they used a lambda function there. But you can also create a normal function which might look something like this:

def customfunc(val):
    if val>=1000:
        format='{:,.0f}'
    if val<1000 and val>=1:
        format='{:,.2f}'
    if val<1:
        format='{:,.5f}'
    return format

df.style.format({0:customfunc})

This should style your first column like described in your problem. If the columns has a name you have to adjust it accordingly. If you have trouble see the documentation linked abve there are more examples.

CodePudding user response:

Just to have it visually clear, this is how it looks now: https://i.stack.imgur.com/Hbz0S.png

That's my line of code: df.style.format({'Price': customfunc})

  •  Tags:  
  • Related