python列表到带有列标题的dataframe并删除数据类型

2024-04-29 14:57:34 发布

您现在位置:Python中文网/ 问答频道 /正文

希望有人能帮我写一个高效的代码。我对python相当陌生,不是最有效率的。在

我有一个到SQL数据库的ODBC连接,下面是它的代码:

import pyodbc
import pandas as pd
import csv

cnxn = pyodbc.connect("DSN=acc_DB")
cursor = cnxn.cursor()
cursor.execute("select top 10 * from Table_XX")
rows = cursor.fetchall()

从这里我得到的是:

enter image description here

enter image description here

然后我把它放到一个数据帧中,然后用这个代码输出到一个csv

^{pr2}$

问题是:

  1. DF无法识别列名,列的值只有0

    1. 列类型被转换为十进制(“xxx”)也被捕获到df中 Masked sensitive information with blue

我如何将它以表格式放入Dataframe中,表格式包含列标题而没有列类型??就像我在mssqlmanagementstudio上执行的SQL查询一样? enter image description here


Tags: csv代码import数据库类型pandassqlas
1条回答
网友
1楼 · 发布于 2024-04-29 14:57:34

如果希望DataFrame包含列名,可以这样做

crsr = cnxn.cursor()
rows = crsr.execute('select top 10 * from Table_XX').fetchall()
df = pd.DataFrame.from_records(rows, columns=[x[0] for x in crsr.description])

然后用列标题将结果转储到CSV

^{pr2}$

相关问题 更多 >