pandas란 python 에서 사용하는 데이터 분석, 전처리 등을 쉽게 하기 위해 사용되는 라이브러리입니다.
응용해서 사용하는 방법은 모르지만 pandas 는 굉장히 빠르기 때문에 저는 종종 mysql db 데이터를 csv로 추출할 때 사용하곤 합니다.
이번 글에서는 pandas로 데이터를 추출하는 방법에 대해 소개해드리겠습니다.

test data

mysql> select * from index_test limit 10;
+----+------+--------------------------------------+
| a  | b    | c                                    |
+----+------+--------------------------------------+
|  1 |    1 | 3ac31cef-f30a-11e9-8dce-0242ac110005 |
|  2 |   47 | 3ac34312-f30a-11e9-8dce-0242ac110005 |
|  3 |   31 | 3ac365be-f30a-11e9-8dce-0242ac110005 |
|  4 |   14 | 3ac3777e-f30a-11e9-8dce-0242ac110005 |
|  5 |   80 | 3ac389fe-f30a-11e9-8dce-0242ac110005 |
|  6 |   56 | 3ac38e36-f30a-11e9-8dce-0242ac110005 |
|  7 |   42 | 3ac3930f-f30a-11e9-8dce-0242ac110005 |
|  8 |   39 | 3ac3982e-f30a-11e9-8dce-0242ac110005 |
|  9 |   70 | 3ac3ac5e-f30a-11e9-8dce-0242ac110005 |
| 10 |   32 | 3ac3d36a-f30a-11e9-8dce-0242ac110005 |
+----+------+--------------------------------------+

mysql> select count(*) from index_test;
+----------+
| count(*) |
+----------+
|  1000000 |
+----------+
1 row in set (0.69 sec)

=> 백만건 데이터를 csv 로 저장할 것

code #1 pandas 미사용


import pymysql
from datetime import datetime

print('START TIME : ',str(datetime.now())[10:19] )

def fwrite():
    with open('normal_output.csv','a') as f:
        f.writelines(text[:-1]+'\n')   ## 각 row 맨 마지막 , 제거용

conn=pymysql.connect(host='localhost',port=3310,user='root',password='test123',db='testdb')
c=conn.cursor()

sql="select * from index_test"
c.execute(sql)
rows=c.fetchall()

for i in rows:    
    text=''
    for j in i:
        j=str(j)
        text=text+j+','
    fwrite()

print('END TIME : ',str(datetime.now())[10:19] )

c.close()
conn.close()
AL01542225:python nhn$ python pandas_test2.py
START TIME :   16:51:57
END TIME :   16:53:42

=>65초 소요

code #2 pandas 사용

import pandas
import pymysql
from datetime import datetime

print('START TIME : ',str(datetime.now())[10:19] )

conn=pymysql.connect(host='localhost',port=3310,user='root',password='test123',db='testdb')
sql="select * from index_test"

result = pandas.read_sql_query(sql,conn)
result.to_csv(r'pandas_output.csv',index=False)

print('END TIME : ',str(datetime.now())[10:19] )

conn.close()
AL01542225:python nhn$ python pandas_test.py
START TIME :   16:50:56
END TIME :   16:51:12

=> 16초 소요