常用的数据存储介质是数据库和csv文件,pandas模块包含了相应的API对数据进行输入和输出:
CSV文件把数据以逗号为字段分隔符,回车换行为行分隔符,pandas使用read_csv()函数来读取csv文件,以to_csv()函数把数据存储为csv。
1,read_csv()
read_csv()函数的参数非常多,
pandas.read_csv(filepath_or_buffer, sep=‘, ‘, delim_whitespace=False, header=‘infer‘, names=None, index_col=None, usecols=None,...)
下面主要介绍最常用的参数:
2,to_csv()
to_csv()函数用于把数据写入到csv文件中
to_csv(path_or_buf,sep,na_rep=‘,‘,columns=None,header=True,index=True,...)
重要参数注释:
执行SQL查询,把数据写入到DataFrame对象中
1,read_sql()
read_sql()函数用于执行SQL查询,把数据写入到DateFrame对象中:
pandas.read_sql(sql, con, index_col=None, chunksize=None)
pandas.read_sql_query(sql, con, index_col=None, chunksize=None)
参数注释:
2,to_sql()
把数据写入到数据库中的表中:
DataFrame.to_sql(name, con, schema=None, if_exists=‘fail‘, index=True, index_label=None, chunksize=None, method=None)
参数注释:
举个例子,从一个数据库中查询数据,插入到SQL Server数据库中:
import psycopg2 import pandas as pd from sqlalchemy import create_engine con=psycopg2.connect(dbname= ‘db_name‘, host=‘db_host‘, port= ‘5439‘, user= ‘‘, password= ‘‘) engine=create_engine(‘mssql+pymssql://user:password@host/db_name?charset=utf8‘,echo=False) sql=""" select ... """ data_frame = pd.read_sql(sql, con) data_frame.to_sql(‘out_table‘, con=engine, if_exists=‘append‘,index = False, schema=‘dbo‘)
参考文档:
SQLAlchemy连接SQLserver数据库及常用的DB操作
原文:https://www.cnblogs.com/ljhdo/p/10881708.html