使用python将SQL表输出为csv,未显示正确的小数位数

问题描述

我正在尝试将SQL中的表([dbo]。[temporary_table])作为csv输出。有2列包含四舍五入到小数点后四位的数字,但我想将它们四舍五入到小数点后两位。

这是我要输出为csv的SQL表:

enter image description here

这是我用来将该表输出为csv的python代码:

import pandas as pd
import numpy as np
import pyodbc
import pandas as pd 
import xlsxwriter
import csv

sql_conn = pyodbc.connect('DRIVER={DRIVER_NAME}; SERVER=SERVER_NAME; DATABASE=DATABASE_NAME; Trusted_Connection=yes') 

query = """select  [Name],cast([Debits] as decimal(19,2)) as 'Debits',cast([Credits] as decimal(19,2)) as 'Credits'
                  from [dbo].[temporary_table]"""
  
                                    
df = pd.read_sql(query,sql_conn)

file_out = 'C:\\Desktop\\Outputs\\testfile.csv'

df.to_csv(file_out,index = False,header=True,quoting=csv.QUOTE_NONE)

当我在记事本中打开csv文件时,仅最后两行正确取整。我猜这是因为小数位不是0。有没有办法使第一行达到50.00而不仅仅是50.0?

这是我在记事本中打开csv文件时看到的:

enter image description here

这就是我想要的:

enter image description here

如果有人能够提供帮助,我将非常感激。

解决方法

Pandas to_csv有一个float_format参数,它将强制将数据帧中的float dtypes设置为指定的格式。

df.to_csv(file_out,index = False,float_format="%.2f",header=True,quoting=csv.QUOTE_NONE)

链接到pandas.to_csv docsstring format docs,但是似乎需要“%.2f”。

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...