Home > database >  Style.format column in dataframe to absolute values
Style.format column in dataframe to absolute values

Time:01-29

I have the following problem. I have a column in a dataframe (let's call it df['Price']) and I need to format in to two decimal places, but for negative values I need the minus sign gone, since I already have a coloring formatting which colors me in red the negative values.

df.style.format({'Price': '{:,.2f}'})

This is the generic formatting which works fine, but how do I change this to solve my problem? I basically need to send the absolute values of the column to formatting instead the actual values.

CodePudding user response:

From the pandas documentation you can pass a callable as formatter. Therefore you can just take the absolute value.

df.style.format({'Price': lambda x: f"{abs(x):,.2f}"})

CodePudding user response:

You can pass a callable to .format as well – see https://pandas.pydata.org/pandas-docs/stable/user_guide/style.html#Formatting-Values.

This should do the trick:

df.style.format({'Price': lambda value: f'{abs(value):,.2f}'})
  •  Tags:  
  • Related