pandas 数据读写

  1. 从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)
  1. 以utf8编码写到excel文件。默认unicode编码的df才能写excel
writer = pd.ExcelWriter('excel文件名', engine='openpyxl')
df.to_excel(writer, encoding='utf8', index=False)
writer.save()
writer.close()
  1. 多个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)
  1. 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)

# 关闭mysql连接
engine.dispose()
  1. 执行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`")
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值