python - 圆形 Pandas 数据框/系列

标签 python pandas dataframe

我在 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/

相关文章:

java - 将(“decimal(32,9)”转换为输入值0的科学值0E-9

python - 多索引合并返回空 df 但连接应该有效

python - 如何从 WTForms 中的 SelectField 获取值(非键)数据

python - 将 YYYYMXX 转换为 pandas 数据框中的日期

python - 当pandas中有混合列数据时添加条件滚动计数

python - 如何标准化 pandas DataFrame 中行之间的字符串?

python - Tensorflow:如何在序列长度不同的 RNN 输出中添加偏差

python - 如何更改python数据框的内容?

Python:类型错误:不可散列的类型: 'slice'

python - 用 Pandas 加载大 CSV 文件