python - 在 0.05 附近四舍五入,从结果中删除一位数
问题描述
我有两列带有数字数据的熊猫表(dtype flaot64)。我已将每一列四舍五入到小数点后 2 位,然后使用函数将其四舍五入到 0.5 附近,但由于某种原因,只有一列被四舍五入为 0.05,第二列被四舍五入但错过了第二位。
这是一个假的例子,它可以工作并显示流程:
table=pd.DataFrame({'A': [0.62435, 0.542345,0.213452],
'B': [0.22426,0.15779,0.30346]})
#function for round to near 0.5:
def custom_round(x, base=5):
return base * round(float(x)/base)
table['A'] = table['A'].astype(float).round(2).apply(lambda x: custom_round(x, base=.05))
table['B'] = table['B'].astype(float).round(2).apply(lambda x: custom_round(x, base=.05))
table
>>>
A B
0 0.60 0.20
1 0.55 0.15
2 0.20 0.30
但在我的桌子上,我最终得到:
当我在没有函数的情况下运行脚本以接近 0.5 时,我仍然得到两位数:
table['B'] = table['B'].round(2)
我的问题是为什么会发生这种情况?以及如何修复它以便将两列四舍五入为 0.05 并显示两个数字?
编辑:有人问我如何在我的真实桌子上应用它,所以:
df['A'] = df['A'].astype(float).round(2).apply(lambda x: custom_round(x, base=.05))
df['B']= df['B'].round(2).apply(lambda x: custom_round(x, base=.05))
解决方案
您的数字四舍五入正确。下面我来解释一下,
- 如何显示2位精度?
- 示例数据发生了什么?
1.如何显示2位精度?
如果您真的只想显示两位数,您可以完全跳过舍入函数 ( custom_round
),并在打印数据帧之前运行 this*:
pd.options.display.float_format = '{:,.2f}'.format
这将使浮点值数据以 2 位精度打印。例子:
table=pd.DataFrame({'A': [0.62435, 0.542345,0.213452],
'B': [0.22426,0.18779,0.30346]})
In [1]: table
Out[1]:
A B
0 0.62 0.22
1 0.54 0.19
2 0.21 0.30
2. 示例数据发生了什么?
- 使用与问题中给出的相同数据
table=pd.DataFrame({'A': [0.62435, 0.542345,0.213452],
'B': [0.22426,0.15779,0.30346]})
# execute code with custom_round in the question
In [1]: table
Out[1]:
A B
0 0.60 0.20
1 0.55 0.15
2 0.20 0.30
- 将 B 的中间值设置为 0.18779(四舍五入为 0.20)
table=pd.DataFrame({'A': [0.62435, 0.542345,0.213452],
'B': [0.22426,0.18779,0.30346]})
# execute code with custom_round in the question
In [1]: table
Out[1]:
A B
0 0.60 0.2
1 0.55 0.2
2 0.20 0.3
为什么会这样?
在内部,该数字被四舍五入为两位数精度。当您将表格打印到控制台/ Jupyter 笔记本时,如果它们全为零,pandas 会跳过最后一个值(第 2 位)的打印。因此,数据是两位数精度(例如,0.20),但它仅以一位数精度显示,因为 0.20 = 0.2。
*您也可以使用其他打印方案:pd.options.display.float_format
可以设置为任何可调用的
[...]接受浮点数并返回 具有所需数字格式的字符串。这在某些地方使用,例如 SeriesFormatter。有关示例,请参见 core.format.EngFormatter。
推荐阅读
- javascript - SVG 平移和缩放 JS 插件会引发奇怪的错误?
- java - Java:ArrayIndexOutOfBoundsExeption
- r - 为什么 rowSums 对某些变量有效而对其他变量无效?
- c++ - 初始化右值引用成员
- node.js - 如何将自定义 ObjectId 添加到解析服务器对象?
- tensorflow2.0 - 将 saved_model.pb 文件转换为具有自定义形状的 .tflite 文件时出现问题
- c++ - 使用 Windows 的 C++ SFML 静态链接,Font.cpp 错误
- .net-core - 从 .net core 2.2 迁移到 3.1 - api 404 错误
- json - 从 Lambda 中的 JSON 提取数据,因此它不是未定义的
- java - Java JSONObject 不会将数组转换为 Json?