简体   繁体   English

拉取MS访问表并将它们放在python中的数据框中

[英]Pulling MS access tables and putting them in data frames in python

I have tried many different things to pull the data from Access and put it into a neat data frame. 我尝试了许多不同的东西来从Access中提取数据并将其放入一个整洁的数据框中。 right now my code looks like this. 现在我的代码看起来像这样。

from pandas import DataFrame
import numpy as np

import pyodbc
from sqlalchemy import create_engine

db_file = r'C:\Users\username\file.accdb'
user = 'user'
password = 'pw'

odbc_conn_str = 'DRIVER={Microsoft Access Driver (*.mdb, *.accdb)};DBQ=%s;UID=%s;PWD=%s' % (db_file, user, password)
conn = pyodbc.connect(odbc_conn_str)

cur = conn.cursor()


qry = cur.execute("SELECT * FROM table WHERE INST = '796116'")
dataf = DataFrame(qry.fetchall()) 
print(dataf)

this puts the data into a data frame but the second row is a list. 这会将数据放入数据框,但第二行是列表。 I need the snippet below to be in 4 separate columns, not 2 with a list. 我需要下面的代码段在4个单独的列中,而不是2个列表。

0   (u'RM257095', u'c1', u'796116')
1   (u'RM257097', u'c2', u'796116')
2   (u'RM257043', u'c3', u'796116')
3   (u'RM257044', u'c4', u'796116')

I have used modules like kdb_utils which has a read_query function and it pulled the data from kdb and separated it into a neat dataframe. 我使用了像kdb_utils这样的模块,它有一个read_query函数,它从kdb中提取数据并将其分成一个整齐的数据帧。 Is there anything like this for access or another way to pull the data and neatly put it into a data frame? 有没有这样的访问或其他方式来拉取数据并巧妙地将其放入数据框?

Consider using pandas' direct read_sql method: 考虑使用pandas的直接read_sql方法:

import pyodbc
import pandas as pd
...
cnxn = pyodbc.connect('DRIVER={{Microsoft Access Driver (*.mdb, *.accdb)}};DBQ=' + \
                      '{};Uid={};Pwd={};'.format(db_file, user, password)

query = "SELECT * FROM mytable WHERE INST = '796116'"
dataf = pd.read_sql(query, cnxn)
cnxn.close()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 基于 Python - 在表中提取数据 - Python based - pulling data in tables Python 使用文件字节访问 zip 文件并遍历每个文件以将它们保存到数据帧中返回找不到文件的错误 - Python access a zip file using file bytes and loop over each file to save them into data frames is returning an error of file is not found python中的Mmimic MS Access用于数据输入,并将结果表与其他表连接 - Mmimic MS Access in python for data entry and connect the resulting table with other tables 从表中提取数据时,MySQLdb Python出现500错误 - 500 error with MySQLdb Python when pulling data from tables python:计算数据框的列并将它们添加到新列 - python : Compute columns of data frames and add them to new columns 使用SQLAlchemy和python数据框架替换和更新Postgresql表 - Replace and update Postgresql tables using SQLAlchemy and python data-frames 从 python 中的 MySQL 表创建数据帧的 pandas 列表 - Creating pandas list of data frames from MySQL tables in python 使用Python获取链接表的MS Access源数据库 - Get the MS Access source database of linked tables with Python 如何使用 Python 循环访问 MS Access 表 - How to loop through MS Access tables using Python 使用 Python 在 MS Access 中传输数据 - Transfering Data in MS Access Using Python
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM