Python - 關係型資料庫



我們可以使用pandas庫以及另一個用於實現資料庫連線的附加庫來連線關係型資料庫以分析資料。此包名為sqlalchemy,它提供了可在 python 中使用的完整 SQL 語言功能。

安裝 SQLAlchemy

使用我們在資料科學環境章節中討論過的 Anaconda,安裝非常簡單。假設您已按照本章所述安裝了 Anaconda,請在 Anaconda 提示符視窗中執行以下命令以安裝 SQLAlchemy 包。

conda install sqlalchemy

讀取關係表

我們將使用 Sqlite3 作為我們的關係型資料庫,因為它非常輕量級且易於使用。儘管 SQLAlchemy 庫可以連線到各種關係源,包括 MySql、Oracle 和 Postgresql 以及 Mssql。我們首先建立一個數據庫引擎,然後使用 SQLAlchemy 庫的to_sql函式連線到資料庫引擎。

在下面的示例中,我們透過使用to_sql函式從已經透過讀取 csv 檔案建立的資料框中建立關係表。然後,我們使用 pandas 中的read_sql_query函式來執行和捕獲來自各種 SQL 查詢的結果。

from sqlalchemy import create_engine
import pandas as pd

data = pd.read_csv('/path/input.csv')

# Create the db engine
engine = create_engine('sqlite:///:memory:')

# Store the dataframe as a table
data.to_sql('data_table', engine)

# Query 1 on the relational table
res1 = pd.read_sql_query('SELECT * FROM data_table', engine)
print('Result 1')
print(res1)
print('')

# Query 2 on the relational table
res2 = pd.read_sql_query('SELECT dept,sum(salary) FROM data_table group by dept', engine)
print('Result 2')
print(res2)

當我們執行上述程式碼時,它會產生以下結果。

Result 1
   index  id    name  salary  start_date        dept
0      0   1    Rick  623.30  2012-01-01          IT
1      1   2     Dan  515.20  2013-09-23  Operations
2      2   3   Tusar  611.00  2014-11-15          IT
3      3   4    Ryan  729.00  2014-05-11          HR
4      4   5    Gary  843.25  2015-03-27     Finance
5      5   6   Rasmi  578.00  2013-05-21          IT
6      6   7  Pranab  632.80  2013-07-30  Operations
7      7   8    Guru  722.50  2014-06-17     Finance

Result 2
         dept  sum(salary)
0     Finance      1565.75
1          HR       729.00
2          IT      1812.30
3  Operations      1148.00

將資料插入關係表

我們還可以使用 pandas 中可用的 sql.execute 函式將資料插入關係表。在下面的程式碼中,我們將之前的 csv 檔案作為輸入資料集,將其儲存在關係表中,然後使用 sql.execute 插入另一條記錄。

from sqlalchemy import create_engine
from pandas.io import sql

import pandas as pd

data = pd.read_csv('C:/Users/Rasmi/Documents/pydatasci/input.csv')
engine = create_engine('sqlite:///:memory:')

# Store the Data in a relational table
data.to_sql('data_table', engine)

# Insert another row
sql.execute('INSERT INTO data_table VALUES(?,?,?,?,?,?)', engine, params=[('id',9,'Ruby',711.20,'2015-03-27','IT')])

# Read from the relational table
res = pd.read_sql_query('SELECT ID,Dept,Name,Salary,start_date FROM data_table', engine)
print(res)

當我們執行上述程式碼時,它會產生以下結果。

   id        dept    name  salary  start_date
0   1          IT    Rick  623.30  2012-01-01
1   2  Operations     Dan  515.20  2013-09-23
2   3          IT   Tusar  611.00  2014-11-15
3   4          HR    Ryan  729.00  2014-05-11
4   5     Finance    Gary  843.25  2015-03-27
5   6          IT   Rasmi  578.00  2013-05-21
6   7  Operations  Pranab  632.80  2013-07-30
7   8     Finance    Guru  722.50  2014-06-17
8   9          IT    Ruby  711.20  2015-03-27

從關係表中刪除資料

我們還可以使用 pandas 中可用的 sql.execute 函式從關係表中刪除資料。以下程式碼根據給定的輸入條件刪除一行。

from sqlalchemy import create_engine
from pandas.io import sql

import pandas as pd

data = pd.read_csv('C:/Users/Rasmi/Documents/pydatasci/input.csv')
engine = create_engine('sqlite:///:memory:')
data.to_sql('data_table', engine)

sql.execute('Delete from data_table where name = (?) ', engine,  params=[('Gary')])

res = pd.read_sql_query('SELECT ID,Dept,Name,Salary,start_date FROM data_table', engine)
print(res)

當我們執行上述程式碼時,它會產生以下結果。

   id        dept    name  salary  start_date
0   1          IT    Rick   623.3  2012-01-01
1   2  Operations     Dan   515.2  2013-09-23
2   3          IT   Tusar   611.0  2014-11-15
3   4          HR    Ryan   729.0  2014-05-11
4   6          IT   Rasmi   578.0  2013-05-21
5   7  Operations  Pranab   632.8  2013-07-30
6   8     Finance    Guru   722.5  2014-06-17
廣告

© . All rights reserved.