Ryan Reid
Ryan Reid

Reputation: 249

How do you display values in a pandas dataframe column with 2 decimal places?

What I am looking to do is make it so that regardless of the value, it displays 2 decimal places.

What I have tried thus far:

DF['price'] = DF['price'].apply(lambda x: round(x, 2))

However, the problem is that I wish to display everything in 2 decimal places, but values like 0.5 are staying at 1 decimal place since they don't need to be rounded.

Is there a function I can apply that gives the following type of output:

Current        After Changes
0              0.00
0.5            0.50
1.01           1.01
1.133333       1.13

Ideally, these values will be rounded but I am open to truncating if that is all that works.

Upvotes: 16

Views: 56437

Answers (4)

Ewoud
Ewoud

Reputation: 131

Try:

import pandas as pd
pd.set_option('display.precision', 2)

This causes it to use scientific (exponential) notation when appropriate, and keeps 2 decimal places. It makes the decision about whether to use scientific notation or not on a per-column basis, so if 1 value requires scientific notation, the whole column is displayed that way.

Examples:

0.0012             1.23e-03
0.0123             1.23e-02
100                1.00e+02
1234567890.123456  1.23e+09

Upvotes: 13

Zombraz
Zombraz

Reputation: 373

If you want to only modify the format of your values without doing any operation in pandas, you should just execute the following instruction:

pd.options.display.float_format = "{:,.2f}".format

This forces it not to use scientific notation (exponential notation) and always displays 2 places after the decimal point. It also adds commas.

You should be able to get more info here:

https://pandas.pydata.org/docs/user_guide/options.html#number-formatting

Examples:

0.0012             0.00
0.0123             0.01
1.2345             1.23
12.345             12.35
100                100.00
1234567890.123456  1,234,567,890.12
 

Upvotes: 20

sebrojas
sebrojas

Reputation: 914

I think you want something like this

DF['price'] = DF['price'].apply(lambda x: float("{:.2f}".format(x)))

This applies the change just to that column

Upvotes: 5

maede rayati
maede rayati

Reputation: 786

You have to set the precision for pandas display. Put this on top of your script after importing pandas:

import pandas as pd
pd.set_option('precision', 2)

Upvotes: 4

Related Questions