在实际使用场景中,大部分数据并不是存储在文本或者Excel文件中的,而是一些基于SQL语言的关系型数据库中,比如MySQL。
从SQL中将数据读取为DataFrame对象是非常简单直接的,pandas提供了多个函数用于简化这个过程。
下面以Python内置的sqlite3标准库为例,介绍一下操作过程。
首先是生成数据库:
In [123]: import sqlite3 # 导入这个标准内置库 # 编写一条创建test表的sql语句 In [124]: query = """ ...: CREATE TABLE test ...: (a VARCHAR(20), b VARCHAR(20), c REAL, d integer);""" In [125]: con = sqlite3.connect('mydata.sqlite') # 创建数据库文件,并连接 In [126]: con.execute(query) # 执行sql语句 Out[126]: <sqlite3.Cursor at 0x2417e5535e0> In [127]: con.commit # 提交事务 Out[127]: <function Connection.commit>
再插入几行数据:
# 两个人和一只老鼠的信息 In [129]: data = [('tom', 'male',1.75, 20), ...: ('mary','female',1.60, 18), ...: ('jerry','rat', 0.2, 60)] ...: # 再来一条空数据 In [130]: stmt = "INSERT INTO test VALUES(?,?,?,?)" In [131]: con.executemany(stmt,data) # 执行多个语句 Out[131]: <sqlite3.Cursor at 0x2417e4b9f80> In [132]: con.commit() # 再次提交事务
前面都是往数据库里写入内容,下面我们来读数据:
In [133]: cursor = con.execute('select * from test') # 执行查询语句 In [134]: rows = cursor.fetchall() # 获取查询结果 In [135]: rows Out[135]: [('tom', 'male', 1.75, 20), ('mary', 'female', 1.6, 18), ('jerry', 'rat', 0.2, 60)] In [136]: cursor.description # 看看结果中的列名,其实就是数据表的列名 Out[136]: (('a', None, None, None, None, None, None), ('b', None, None, None, None, None, None), ('c', None, None, None, None, None, None), ('d', None, None, None, None, None, None)) In [137]: pd.DataFrame(rows,columns= [x[0] for x in cursor.description]) Out[137]: a b c d 0 tom male 1.75 20 1 mary female 1.60 18 2 jerry rat 0.20 60
上面最后生成DataFrame时,使用了一个列表推导式来构成列名序列。
例子到这里大致就完成了,但是关于数据库的连接和查询操作实在是够繁琐的,你肯定不想每次都这么来一遍。那么怎么办呢?使用流行的Python的SQL工具包SQLAlchemy,它能简化你的数据库操作。同时,pandas提供了一个read_sql函数,允许你从通用的SQLAlchemy连接中轻松地读取数据。一个典型的操作如下:
In [138]: import sqlalchemy as sqla In [140]: db = sqla.create_engine('sqlite:///mydata.sqlite') # 创建连接 In [141]: pd.read_sql('select * from test', db) # 查询数据并转换为pandas对象 Out[141]: a b c d 0 tom male 1.75 20 1 mary female 1.60 18 2 jerry rat 0.20 60
在Anaconda中,已经默认安装了SQLAlchemy,可以直接使用。如果你的环境中没有SQLAlchemy,请自定安装,或者搜索教程进行学习。