pandas讀取20W資料excel,每999行生成一個查詢sql語句
阿新 • • 發佈:2018-11-05
前言
工作中遇到一個小問題,Oralce資料庫的查詢是不能大於1000條in查詢的,所以需要對檔案進行切割。資料來源是20w的excel資料,於是想到用pandas對其進行讀取,然後每998行生成一個新的sql檔案。
程式碼實現
# coding = utf-8
"""
@author: sy
@file: readexcel.py
@time: 2018/6/15 10:11
@desc:
"""
import pandas as pd
#from multiprocessing.dummy import Pool as ThreadPool
#from functools import partial 本想試下多執行緒
def read_data():
short_data = pd.read_excel('C:/Users/sy/Desktop/split/data.xlsx', sheet_name='Sheet1')
short_data = short_data.fillna(-1)
sql_str = 'select t.policyno from xxxxx t where t.policyno in ('
sum_sql = ''
# pandas 讀取的型別為DataFrame,也是可迭代的物件
for i, excel_policy_no in enumerate (short_data['保單號']):
sum_sql += "'" + str(excel_policy_no) + "',"
if i != 0 and i % 997 == 0:
sum_sql += "'" + str(excel_policy_no) + "');"
sql = sql_str + sum_sql
thread_function(i, sql)
sum_sql = ''
def thread_function(i, sql):
write_sql( 'C:/Users/sy/Desktop/split/' + str(i) + '.sql', sql)
def write_sql(filename, content):
with open(filename, 'a', encoding='utf-8') as f:
f.write(content)
if __name__ == '__main__':
read_data()
總結
耗時多數在讀取20W資料的時候,讀取excel時,一次全讀到記憶體中了,所以比較慢,像pandas自帶的csv讀取,可以進行分塊讀取。excel我查閱了相關官方文件,並沒有看到相應屬性,若有更好的方式歡迎留言討論!