使用機器學習訓練數據時,如果數據量較大可能我們不能夠一次性將數據加載進內存,這時我們需要將數據進行預處理,分批次加載進內存。
下面是代碼作用是將數據從數據庫讀取出來分批次寫入txt文本文件,方便我們做數據的預處理和訓練機器學習模型。
#%%import pymssql as MySQLdb #這里是python3 如果你是python2.x的話,import MySQLdb#數據庫連接屬性hst = '188.10.34.18'usr = 'sa'passwd = 'p@ssw0rd'db = 'HistoryTrace' #總共多少數據allData = 1674333#每個批次多少條數據dataOfEach = 20000#批次batch = ceil(allData/dataOfEach) #文件名global IDctrl IDctrl = 1filename = str(IDctrl)+'.txt' #連接數據庫conn = MySQLdb.connect(host=hst,user=usr,password=passwd,database=db)cur=conn.cursor() while IDctrl<batch: #讀取數據庫 sql = 'SELECT Longitude,Latitude,Altitude,VelComOfLong,VelComOfLati,Aircraft,Section,TimeMinus/ FROM dealed1 where ID>=' + str(IDctrl) + ' and ID <' + str(IDctrl + dataOfEach) cur.execute(sql) rows=cur.fetchall() #寫文件 f = open(filename,'w') f.writelines(str(rows)) #文件名加1 IDctrl+=1 filename = str(IDctrl)+'.txt' #關閉數據庫連接f.close()conn.close()
以上這篇Python從數據庫讀取大量數據批量寫入文件的方法就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支持武林站長站。
新聞熱點
疑難解答