George
George

Reputation: 79

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

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:

Does anyone have a solution for this? Thank you!

Upvotes: 1

Views: 2703

Answers (3)

ozacha
ozacha

Reputation: 1352

Building upon @Code_beginner's answer – the callable should return formatted string as output:

def my_format(val):
    if val >= 1000:
        return f"{val:,.0f}"
    if val >= 1:
        return f"{val:,.2f}"
    return f"{val:,.5f}"

mytable.style.format({'Price': my_format})

Upvotes: 4

George
George

Reputation: 79

Just to have it visually clear, this is how it looks now: enter image description here

That's my line of code:

df.style.format({'Price': customfunc})

Upvotes: 0

Code_beginner
Code_beginner

Reputation: 92

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.

Upvotes: 0

Related Questions