如何舍入pydatatable中的浮动值?

How to round off floating values in pydatatable?

我正在对 datatable 字段进行一些数学运算,如下所示

样本标识符:

py_DT = dt.Frame({'junction' : ['BroadwayCycleTrack-N','BroadwayCycleTrack-N',
                 'Burke Gilman Trail','Burke Gilman Trail','Elliot Bay','Elliot Bay'],
                 'time_window' : ['N','MD','M','M','N','MD'],
                 'total_bus' :[3526,8732,6732,9821,6473,9273] 
                 })

我想计算通过每个路口的公交车的百分比为

代码块

py_DT[:,{'perc_of': f.total_bus/dt.sum(f.total_bus)},by(f.junction)]

这里有一个名为 perc_of 的新字段以浮点数形式保存计算值,例如

0.287649 和 0.712351 用于穿越 BroadwayCycleTrack-N

我在这里尝试使用 dt.math 模块来四舍五入浮点数,因为 DT 中的 F 表达式不允许 python 的 round方法。

代码块:

py_DT[:,{'perc_of': dt.math.trunc(f.total_bus/dt.sum(f.total_bus))},by(f.junction)]

py_DT[:,{'perc_of': dt.math.floor(f.total_bus/dt.sum(f.total_bus))},by(f.junction)]

py_DT[:,{'perc_of': dt.math.ceil(f.total_bus/dt.sum(f.total_bus))},by(f.junction)]

py_DT[:,{'perc_of': dt.math.trunc(f.total_bus/dt.sum(f.total_bus))},by(f.junction)]

他们没有解决将 0.287649 四舍五入到 0.28 或 0.287 的问题,还有其他我应该尝试的功能吗?。我正在搜索它的文档,但找不到合适的文档。

dt.math.rint() 函数 (https://datatable.readthedocs.io/en/latest/api/math.html#rint) 四舍五入到最接近的整数。

没有直接等效于 python 的 round() 功能,但欢迎您在 https://github.com/h2oai/datatable/issues 提出功能请求以实现它。

目前,四舍五入到特定位数可以通过将列乘以 10 的幂,然后四舍五入,然后再次除法来实现:

dt.math.rint(f[0] * 1000) / 1000