Vermillion
Vermillion

Reputation: 1308

pandas.DataFrame.round outputs different numbers of decimal places

Calling round(2) on the following DataFrame results in one column with 2 decimal places, as expected, but the other column has only 1 decimal place.

import pandas as pd

df = pd.DataFrame([
    [0.829, 0.801],
    [0.997, 0.997]
])

df.round(2)

When this is run in a notebook, it outputs:

      0    1
0  0.83  0.8
1  1.00  1.0

I think this is because 0.801 rounds to 0.8, so only one decimal place is needed, and the other row goes to 1.0 instead of 1.00.

But I want to output this DataFrame to a LaTeX table, so I'd prefer the same number of decimal places in both columns. Is there a way to force pandas to output 2 decimal places for all columns?

Upvotes: 2

Views: 483

Answers (2)

Toby Petty
Toby Petty

Reputation: 4660

You can use lambda expressions to map string formatting onto the columns:

df[1] = df[1].apply(lambda x: f"{x:.2f}")

Upvotes: 0

Mark Wang
Mark Wang

Reputation: 2757

Try string formatting,

df.round(2).applymap('{:.2f}'.format)

Upvotes: 1

Related Questions