将SQL转换为Pandas DataFrame执行python操作数据库,本例以sqlLite为例。 一.创建sqlLite数据库并插入数据 为了演示如何将sql转换为Pandas DataFrame对数据进行操作,我们首先用Python创建sqlLite数据库,创建数据表并插入数据。代码中使用了python的sqlite3包。 1.示例数据库名称:test_database 2.示例数据库表名:products,为了操作简单,我们只创建了一个表 3.示例数据:表products只包含了三个字段:product_id,product_name,price 示例数据如下表展示
| product_id | product_name | price |
|---|---|---|
| 1 | Computer | 800 |
| 2 | Printer | 200 |
| 3 | Tablet | 300 |
| 4 | Desk | 450 |
| 5 | Chair | 150 |
4.示例代码:
import sqlite3
conn = sqlite3.connect('test_database')
c = conn.cursor()
c.execute('''
CREATE TABLE IF NOT EXISTS products
([product_id] INTEGER PRIMARY KEY, [product_name] TEXT, [price] INTEGER)
''')
c.execute('''
INSERT INTO products (product_id, product_name, price)
VALUES
(1,'Computer',800),
(2,'Printer',200),
(3,'Tablet',300),
(4,'Desk',450),
(5,'Chair',150)
''')
conn.commit()
保存为demoCreate.py 在Python中执行 python3 demoCreate.py,会在该脚本目录生成test_database, 这个文件就是我们创建的示例数据库及相应数据。
二.转换sql为Pandas查询的两种方法 1.使用Pandas DataFrame 的 read_sql_query方法进行sql查询:
import sqlite3
import pandas as pd
conn = sqlite3.connect('test_database')
sql_query = pd.read_sql_query ('''
SELECT
*
FROM products
''', conn)
df = pd.DataFrame(sql_query, columns = ['product_id', 'product_name', 'price'])
print (df)
将上面的脚本保存为readSQL.py,然后在python环境中执行,正常情况会查询出如下数据结果: product_id product_name price 0 1 Computer 800 1 2 Printer 200 2 3 Tablet 300 3 4 Desk 450 4 5 Chair 150
如果出现ModuleNotFoundError: No module named 'pandas',则需要安装pandas组件: pip3 install pandas 然后再执行即可 2.还有另外一种方法进行查询:
import sqlite3
import pandas as pd
conn = sqlite3.connect('test_database')
c = conn.cursor()
c.execute('''
SELECT
*
FROM products
''')
df = pd.DataFrame(c.fetchall(), columns = ['product_id', 'product_name', 'price'])
print (df)
执行的结果和上面是一样的。
三.转换sql为Pandas查询最大值 通过使用Pandas的方法计算最大值,如下方法:
max_price = df['price'].max()
print (max_price)
完整的代码如下:
import sqlite3
import pandas as pd
conn = sqlite3.connect('test_database')
c = conn.cursor()
c.execute('''
SELECT
*
FROM products
''')
df = pd.DataFrame(c.fetchall(), columns = ['product_id', 'product_name', 'price'])
max_price = df['price'].max()
print (max_price)
在python环境中执行,会得出如下结果:
800