style.format() 和小数列的问题

Problem with style.format() and a decimal column

我正在尝试将 style.format 函数应用于数据框以调整小数位数,因为 round() 函数不适用。 (我不明白为什么。)

df中的数据格式为123.0432.0543.0,但我需要它们有两位小数(例如,123.00).

我已使用函数 df.dtypes 验证该列的类型为 float

我尝试应用以下内容:

import pandas.io.formats.style
import pandas as pd

df['DD'] = df[['Quantity']].style.format("{:.2%}")
df

DD 字段中出现以下内容:

<pandas.io.formats.style.Styler object at 0x7f...

round() 函数对该列也不起作用。

可以做什么?

.style 返回一个 Styler 对象 (reference)。 Styler 对象可以用不同的方式格式化。这在您的 DD 专栏中没有发生;你只完成了一半。

您可以使用

格式化数据框
df.style.format({'Quantity': "{:.2%}"})

this SO post 中所述。