我对数据表字段进行一些数学运算,如下所示
设备标识符示例:
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 的新字段以 float 形式保存计算值,例如
0.287649 和 0.712351 用于穿越 BroadwayCycleTrack-N
这里我试图利用 dt.math 模块对 float 进行四舍五入,因为 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
关于python - 如何舍入pydatatable中的 float 值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59560330/