Python中对bounding box浮点数保留6位小数失败求助
解决方案
处理Bounding Box列表
直接用嵌套列表推导式遍历每个数值,执行四舍五入保留6位小数:
bbox_list = [[7.426758, 47.398349, 7.850835593464796, 47.68617800490421], [7.850835593464796, 47.398349, 8.274913186929592, 47.68617800490421], [8.274913186929592, 47.398349, 8.698990780394388, 47.68617800490421]] # 保留6位小数 rounded_bbox_list = [[round(num, 6) for num in bbox] for bbox in bbox_list] print(rounded_bbox_list)
输出结果:
[[7.426758, 47.398349, 7.850836, 47.686178], [7.850836, 47.398349, 8.274913, 47.686178], [8.274913, 47.398349, 8.698991, 47.686178]]
处理Bounding Box字典
先把字符串值分割为单个浮点数,四舍五入后可选择保留数值列表或重新拼接成字符串:
方式1:保留数值列表作为字典值
bbox_dict = {49: '7.850835593464796,49.12532302942521,8.274913186929592,49.413152034329414', 17: '7.850835593464796,47.9740070098084,8.274913186929592,48.26183601471261', 71: '10.395301154253572,49.70098103923361,10.819378747718368,49.988810044137814'} rounded_bbox_dict = {} for key, val in bbox_dict.items(): nums = [round(float(num_str), 6) for num_str in val.split(',')] rounded_bbox_dict[key] = nums print(rounded_bbox_dict)
输出结果:
{49: [7.850836, 49.125323, 8.274913, 49.413152], 17: [7.850836, 47.974007, 8.274913, 48.261836], 71: [10.395301, 49.700981, 10.819379, 49.98881]}
方式2:重新拼接为字符串(保持原格式)
rounded_bbox_dict_str = {} for key, val in bbox_dict.items(): nums = [str(round(float(num_str), 6)) for num_str in val.split(',')] rounded_bbox_dict_str[key] = ','.join(nums) print(rounded_bbox_dict_str)
输出结果:
{49: '7.850836,49.125323,8.274913,49.413152', 17: '7.850836,47.974007,8.274913,48.261836', 71: '10.395301,49.700981,10.819379,49.98881'}
Pandas正确处理方式
如果坚持用Pandas,可将数据转成DataFrame后调用round()方法,再转回原格式:
处理列表
import pandas as pd df = pd.DataFrame(bbox_list) rounded_df = df.round(6) rounded_bbox_list_pd = rounded_df.values.tolist()
处理字典
# 字典转DataFrame并转换数值类型 df_dict = pd.DataFrame([val.split(',') for val in bbox_dict.values()], index=bbox_dict.keys()).astype(float) rounded_df_dict = df_dict.round(6) # 转回数值列表格式的字典 rounded_bbox_dict_pd = rounded_df_dict.to_dict('index') # 转回字符串格式的字典 rounded_bbox_dict_str_pd = {k: ','.join(map(str, v)) for k, v in rounded_df_dict.to_dict('index').items()}
内容的提问来源于stack exchange,提问作者Daniel AG
相关产品推荐
相关产品推荐

