我在 pandas 数据框中有一列看起来像这样(更长但这是前几行):
>df_fill['col1']
0 5987.8866699999998672865
1 52215.5966699999989941716
2 201.8966700000000003001
3 3.8199999999999998401
我想将整列四舍五入到小数点后 5 位。我可以将它四舍五入为整数,但不能四舍五入到小数点后的任何数字。列的类型是 float。
> np.around(df_fill['col1'], 0)
0 5988
1 52216
2 202
3 4
> np.around(df_fill['col1'], 5)
0 5987.8866699999998672865
1 52215.5966699999989941716
2 201.8966700000000003001
3 3.8199999999999998401
> (df_fill['col1']).round()
0 5988
1 52216
2 202
3 4
>(df_fill['col1']).round(5)
0 5987.8866699999998672865
1 52215.5966699999989941716
2 201.8966700000000003001
3 3.8199999999999998401
> (df_fill['col1']).round(decimals=5)
0 5987.8866699999998672865
1 52215.5966699999989941716
2 201.8966700000000003001
3 3.8199999999999998401
> str((df_fill['col1']).round(decimals=5))
'0 5987.8866699999998672865\n1 52215.5966699999989941716\n2 201.8966700000000003001\n3 3.8199999999999998401\
我在这里错过了什么?
最佳答案
花车 can only represent a subset of the real numbers .它只能精确地表示那些是两个负幂之和的小数(“二进制分数”)。 将 float 舍入为 5 位后,新的 float 可能不是具有 5 位小数的实数,因为小数部分可能无法精确表示为二进制分数。相反,舍入返回最接近该实数的 float 。
如果你设置了
pd.options.display.float_format = '{:.23g}'.format
然后 Pandas 将在其 float 的字符串表示中显示最多 23 位数字:
import pandas as pd
pd.options.display.float_format = '{:.23g}'.format
df_fill = pd.DataFrame({'col1':[ 5987.8866699999998672865, 52215.5966699999989941716,
201.8966700000000003001, 3.8199999999999998401]})
# col1
# 0 5987.8866699999998672865
# 1 52215.596669999998994172
# 2 201.89667000000000030013
# 3 3.8199999999999998401279
print(df_fill['col1'].round(5))
# 0 5987.8866699999998672865
# 1 52215.596669999998994172
# 2 201.89667000000000030013
# 3 3.8199999999999998401279
# Name: col1, dtype: float64
但是如果您将 float_format 设置为显示 5 个十进制数字:
pd.options.display.float_format = '{:.5f}'.format
然后
print(df_fill['col1'].round(5))
产量
0 5987.88667
1 52215.59667
2 201.89667
3 3.82000
Name: col1, dtype: float64
注意底层 float 没有改变;仅显示方式。
关于python - 圆形 Pandas 数据框/系列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32399132/