- 从zip文件中读取数据
import pandas as pd
import zipfile
file_path = 'zip文件路径'
with zipfile.ZipFile(file_path, 'r') as z:
f = z.open('zip中的csv文件名')
df = pd.read_csv(f, dtype=str)
- 以utf8编码写到excel文件。默认unicode编码的df才能写excel
writer = pd.ExcelWriter('excel文件名', engine='openpyxl')
df.to_excel(writer, encoding='utf8', index=False)
writer.save()
writer.close()
- 多个df写到同一个excel的不同sheet
import pandas as pd
import os
from openpyxl import load_workbook
def excelAddSheet(dataframe, outfile, name):
writer = pd.ExcelWriter(outfile)
if os.path.exists(outfile) != True:
dataframe.to_excel(writer, name, index=None)
else:
book = load_workbook(outfile)
writer = pd.ExcelWriter(outfile, engine='openpyxl')
writer.book = book
writer.sheets = dict((ws.title, ws) for ws in book.worksheets)
df2.to_excel(writer, name, index=False)
writer.save()
writer.close()
df = pd.DataFrame({'a':[1,2,3]})
excel_name = 'excel_file.xlsx'
for i in xrange(10):
df['a'] =1*i
sheet_name = str(i)
excelAddSheet(df, excel_name, sheet_name)
- pandas读取mysql数据
import pandas as pd
from sqlalchemy import create_engine
host =''
username =''
password =''
db =''
engine = create_engine('mysql+pymysql://%s:%s@%s:3306/%s?charset=utf8' % (username, password, host, db))
sql = 'select * from table_name'
df = pd.read_sql(sql, con=engine)
engine.dispose()
- 执行mysql命令
import pymysql
host =''
username =''
password =''
db =''
conn = pymysql.connect(host=host, port=3306, user=username, passwd=password, db=db)
conn.autocommit(True)
cur = conn.cursor()
cur.execute("update table set `column`=`value`")