使用機器學習訓練數據時,如果數據量較大可能我們不能夠一次性將數據加載進內存,這時我們需要將數據進行預處理,分批次加載進內存。
下面是代碼作用是將數據從數據庫讀取出來分批次寫入txt文本文件,方便我們做數據的預處理和訓練機器學習模型。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
|
#%% 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 = 1 filename = 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從數據庫讀取大量數據批量寫入文件的方法就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支持服務器之家。
原文鏈接:https://blog.csdn.net/Tan_HandSome/article/details/79261413