问题1:如何从数据库中读取整个表数据到DataFrame中?
首先,来看很容易想到的的办法
def read_table_by_name(self, table_name):
"""
读取table_name表
:return: dataframe对象 所有的评价对象及其数据
"""
field_list = [] # target表的所有字段的列表
field_data = [] # 存放某一字段的所有数据
frame_data = pd.DataFrame() self._cursor = self._connect.cursor()
sql = "select COLUMN_NAME from information_schema.COLUMNS where table_name = '%s'"
self._cursor.execute(sql % table_name)
results = self._cursor.fetchall()
for row in results:
field_list.append(row[0]) name_sql = "select %s from %s"
i = 0
for field in field_list:
self._cursor.execute(name_sql % (field, table_name))
column_data = self._cursor.fetchall()
field_data.clear()
for j in range(len(column_data)):
field_data.append(column_data[j][0])
frame_data.insert(i, field, field_data) # frame_data 插入数据 i += 1 return frame_data
看起来,十分麻烦。那么有没有简单的办法呢?当然有,目前我已知的有以下几种:
1:使用pandas.io.sql模块中sql.read_sql_table(table_name,conn)直接将一个table转到dataframe中
import pandas as pd
from sqlalchemy import create_engine
engine = create_engine('mysql+pymysql://root:123456@localhost:3306/test')
result = pd.io.sql.read_sql_table('employee', engine)
print(type(result), '\n', result)
注意:read_sql_table 仅支持 SQLAlchemy 连接
输出结果如下:
2:使用pandas.io.sql模块中的sql.read_sql_query(sql_str,conn)或者sql.read_sql(sql_str,conn),效果相同,都使用sql语句
import pandas as pd
import pymysql
from sqlalchemy import create_engine
# conn = pymysql.connect(host='127.0.0.1', port=3306, user='root', passwd='123456', db='test')
engine = create_engine('mysql+pymysql://root:123456@localhost:3306/test')
sql_str = 'select * from employee'
result = pd.io.sql.read_sql_query(sql_str, engine)
print(type(result), '\n', result)
import pandas as pd
import pymysql
from sqlalchemy import create_engine
conn = pymysql.connect(host='127.0.0.1', port=3306, user='root', passwd='', db='test')
# engine = create_engine('mysql+pymysql://root:123456@localhost:3306/test')
sql_str = 'select * from employee'
result = pd.io.sql.read_sql_query(sql_str, conn)
print(type(result), '\n', result)
注意:read_sql_query 不仅支持 SQLAlchemy 连接,pymysql也可以
问题2:如何从数据库中读取表的指定列的数据到DataFrame中?
先来看比较容易想到的办法:
def read_indexs_by_index(self, table_name, index_list):
"""
根据选择的指标名列表读取table_name表
:param self:
:param table_name: 表名
:param index_list: 指定列的列表
:return:
"""
index_data = []
frame_data = pd.DataFrame()
sql = "select %s from %s"
i = 0
for index in index_list:
self._cursor.execute(sql % (index, table_name))
column_data = self._cursor.fetchall()
index_data.clear()
for j in range(len(column_data)):
index_data.append(float(column_data[j][0]))
frame_data.insert(i, index, index_data) # frame_data 插入数据
i += 1 return frame_data
再看使用使用 pd.io.sql.read_sql_query模块的方法:
def read_indexs_by_index(self, table_name, index_list):
"""
根据选择的指标名列表读取table_name表
:param self:
:param table_name:
:param index_list:
:return:
"""
sql = "select * from %s"
df = pd.io.sql.read_sql_query((sql % table_name), self._connect) data_frame = df.loc[list(range(0, df.shape[0])), index_list] # df.loc[:,index_list]也可以 return data_frame
只需要四行