当我使用 head() 或 tail() 时,我希望仅对 DataFrame 中的值进行舍入以用于显示目的,但我希望 DataFrame 保留原始值。
我尝试使用 round 方法,但它改变了原始 DataFrame 中的值。我不希望每次都为此目的创建单独的副本。
除了创建单独的副本之外还有其他方法吗?
我在查看值时遇到困难,因为某些列具有 e^10 符号。我只想看看最多两到三位小数,而不是一直盯着指数值。
您可以临时更改显示选项:
with pd.option_context('display.precision', 3):
print(df.head())
0 1 2 3 4
0 -0.462 -0.698 -2.030 0.766 -1.670
1 0.925 0.603 -1.062 1.026 -0.096
2 0.589 0.819 -1.040 -0.162 2.467
3 -1.169 0.637 -0.435 0.584 1.232
4 -0.704 -0.623 1.226 0.507 0.507
或永久更改:
pd.set_option('display.precision', 3)
一个简单的
print(df.head().round(3))
在这种情况下也可以工作。他们不会就地更改 DataFrame。
如果你想改变特定DataFrame的精度,你可以使用panda的
Styler.format
。要使 DataFrame 中的每一列都具有相同的精度,您可以使用:
df = pd.DataFrame(np.random.random(size=(15, 4)), columns=list('ABCD'))
df.head().style.format(precision=2)
A B C D
0 0.24 1.00 0.69 0.63
1 0.99 0.22 0.09 0.34
2 0.33 0.24 0.86 0.04
3 0.65 0.13 0.54 0.18
4 0.50 0.70 0.44 0.19
要使特定列具有不同的精度,您可以使用字典对其进行格式化:
df.head().style.format({'D':'{:0.5f}'},precision=2)
A B C D
0 0.24 1.00 0.69 0.63088
1 0.99 0.22 0.09 0.34297
2 0.33 0.24 0.86 0.03709
3 0.65 0.13 0.54 0.18494
4 0.50 0.70 0.44 0.18531
pd.set_option('display.precision', 3)
不适用于 Styler
对象。要在 pd.set_option
对象上使用 Styler
,请改用 pd.set_option('styler.format.precision', 3)
。
import numpy as np
import pandas as pd
from IPython.display import display
pd.set_option('styler.format.precision', 3)
df = pd.DataFrame(
np.random.random(size=(2, 3))
)
display(df.style.set_caption("Styler precision"))
``