使用機器學習訓練數(shù)據(jù)時,如果數(shù)據(jù)量較大可能我們不能夠一次性將數(shù)據(jù)加載進內(nèi)存,這時我們需要將數(shù)據(jù)進行預處理,分批次加載進內(nèi)存。
下面是代碼作用是將數(shù)據(jù)從數(shù)據(jù)庫讀取出來分批次寫入txt文本文件,方便我們做數(shù)據(jù)的預處理和訓練機器學習模型。
#%%import pymssql as MySQLdb #這里是python3 如果你是python2.x的話,import MySQLdb#數(shù)據(jù)庫連接屬性hst = '188.10.34.18'usr = 'sa'passwd = 'p@ssw0rd'db = 'HistoryTrace' #總共多少數(shù)據(jù)allData = 1674333#每個批次多少條數(shù)據(jù)dataOfEach = 20000#批次batch = ceil(allData/dataOfEach) #文件名global IDctrl IDctrl = 1filename = str(IDctrl)+'.txt' #連接數(shù)據(jù)庫conn = MySQLdb.connect(host=hst,user=usr,password=passwd,database=db)cur=conn.cursor() while IDctrl<batch: #讀取數(shù)據(jù)庫 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' #關閉數(shù)據(jù)庫連接f.close()conn.close()
以上這篇Python從數(shù)據(jù)庫讀取大量數(shù)據(jù)批量寫入文件的方法就是小編分享給大家的全部內(nèi)容了,希望能給大家一個參考,也希望大家多多支持VEVB武林網(wǎng)。
|
新聞熱點
疑難解答
圖片精選