[英]Output SQL table as csv using python not displaying correct decimal places
I am trying to output a table in SQL ([dbo].[temporary_table]) as a csv.我正在尝试将 SQL ([dbo].[temporary_table]) 中的表作为 csv 输出。 There are 2 columns that contain numbers rounded to 4 decimal places but I want to output them rounded to 2 decimal places.
有 2 列包含四舍五入到小数点后 4 位的数字,但我想将它们输出到小数点后 2 位。
This is the SQL table I want to output as csv:这是我想输出为 csv 的 SQL 表:
And this is the python code I'm using to output that table as csv:这是我用来将该表输出为 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)
When I open the csv file in Notepad only the last 2 rows are rounded correctly.当我在记事本中打开 csv 文件时,只有最后两行正确四舍五入。 I'm guessing this is because the decimal places are not 0s.
我猜这是因为小数位不是 0。 Is there a way to get the first row to be 50.00 and not just 50.0?
有没有办法让第一行是 50.00 而不仅仅是 50.0?
This is what I see when I open the csv file in Notepad:这是我在记事本中打开 csv 文件时看到的:
And this is what I want:这就是我想要的:
If anyone is able to help I'd be very grateful.如果有人能够提供帮助,我将不胜感激。
Pandas to_csv has a float_format argument that will force float dtypes in the dataframe to the specified format. Pandas to_csv 有一个 float_format 参数,它将强制数据框中的 float dtypes 为指定的格式。
df.to_csv(file_out, index = False, float_format="%.2f", header=True, quoting=csv.QUOTE_NONE)
Links to pandas.to_csv docs and string format docs , but seems like "%.2f" is what you need.链接到pandas.to_csv docs和string format docs ,但似乎“%.2f”正是您所需要的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.