热线电话:13121318867

登录
首页精彩阅读厉害了,在Pandas中用SQL来查询数据,效率超高
厉害了,在Pandas中用SQL来查询数据,效率超高
2022-03-22
收藏
厉害了,在Pandas中用<a href='/map/sql/' style='color:#000;font-size:inherit;'>SQL</a>来查询数据,效率超高

作者:俊欣

来源:关于数据分析与可视化

今天我们继续来讲一下PandasSQL之间的联用,我们其实也可以在Pandas当中使用SQL语句来筛选数据,通过Pandasql模块来实现该想法,首先我们来安装一下该模块

pip install pandasql

要是你目前正在使用jupyter notebook,也可以这么来下载

!pip install pandasql 

导入数据

我们首先导入数据

import pandas as pd from pandasql import sqldf
df = pd.read_csv("Dummy_Sales_Data_v1.csv", sep=",")
df.head()

output

厉害了,在Pandas中用<a href='/map/sql/' style='color:#000;font-size:inherit;'>SQL</a>来查询数据,效率超高

我们先对导入的数据集做一个初步的探索性分析,

df.info()

output

<class 'pandas.core.frame.DataFrame'> RangeIndex: 9999 entries, 0 to 9998 Data columns (total 12 columns):
 #   Column               Non-Null Count  Dtype  
---  ------               --------------  ----- 0 OrderID 9999 non-null int64 1 Quantity 9999 non-null int64 2 UnitPrice(USD) 9999 non-null int64 3 Status 9999 non-null object 4 OrderDate 9999 non-null object 5 Product_Category 9963 non-null object 6 Sales_Manager 9999 non-null object 7 Shipping_Cost(USD) 9999 non-null int64 8 Delivery_Time(Days) 9948 non-null float64 9 Shipping_Address 9999 non-null object 10 Product_Code 9999 non-null object 11 OrderCode 9999 non-null int64  
dtypes: float64(1), int64(5), object(6)
memory usage: 937.5+ KB

再开始进一步的数据筛选之前,我们再对数据集的列名做一个转换,代码如下

df.rename(columns={"Shipping_Cost(USD)":"ShippingCost_USD", "UnitPrice(USD)":"UnitPrice_USD", "Delivery_Time(Days)":"Delivery_Time_Days"},
          inplace=True)
df.info()

output

<class 'pandas.core.frame.DataFrame'> RangeIndex: 9999 entries, 0 to 9998 Data columns (total 12 columns):
 #   Column              Non-Null Count  Dtype  
---  ------              --------------  ----- 0 OrderID 9999 non-null int64 1 Quantity 9999 non-null int64 2 UnitPrice_USD 9999 non-null int64 3 Status 9999 non-null object 4 OrderDate 9999 non-null object 5 Product_Category 9963 non-null object 6 Sales_Manager 9999 non-null object 7 ShippingCost_USD 9999 non-null int64 8 Delivery_Time_Days 9948 non-null float64 9 Shipping_Address 9999 non-null object 10 Product_Code 9999 non-null object 11 OrderCode 9999 non-null int64  
dtypes: float64(1), int64(5), object(6)
memory usage: 937.5+ KB

SQL筛选出若干列来

我们先尝试筛选出OrderIDQuantitySales_ManagerStatus等若干列数据,用SQL语句应该是这么来写的

SELECT OrderID, Quantity, Sales_Manager, 
Status, Shipping_Address, ShippingCost_USD 
FROM df 

Pandas模块联用的时候就这么来写

query = "SELECT OrderID, Quantity, Sales_Manager,
Status, Shipping_Address, ShippingCost_USD 
FROM df" df_orders = sqldf(query) df_orders.head() 

output

厉害了,在Pandas中用<a href='/map/sql/' style='color:#000;font-size:inherit;'>SQL</a>来查询数据,效率超高

SQL中带WHERE条件筛选

我们在SQL语句当中添加指定的条件进而来筛选数据,代码如下

query = "SELECT * 
        FROM df_orders 
        WHERE Shipping_Address = 'Kenya'" df_kenya = sqldf(query) df_kenya.head() 

output

厉害了,在Pandas中用<a href='/map/sql/' style='color:#000;font-size:inherit;'>SQL</a>来查询数据,效率超高

而要是条件不止一个,则用AND来连接各个条件,代码如下

query = "SELECT *  FROM df_orders  WHERE Shipping_Address = 'Kenya'  AND Quantity < 40  AND Status IN ('Shipped', 'Delivered')"
df_kenya = sqldf(query)
df_kenya.head() 

output

厉害了,在Pandas中用<a href='/map/sql/' style='color:#000;font-size:inherit;'>SQL</a>来查询数据,效率超高

分组

同理我们可以调用SQL当中的GROUP BY来对筛选出来的数据进行分组,代码如下

query = "SELECT Shipping_Address,  COUNT(OrderID) AS Orders  FROM df_orders  GROUP BY Shipping_Address"

df_group = sqldf(query)
df_group.head(10) 

output

厉害了,在Pandas中用<a href='/map/sql/' style='color:#000;font-size:inherit;'>SQL</a>来查询数据,效率超高

排序

而排序在SQL当中则是用ORDER BY,代码如下

query = "SELECT Shipping_Address,  COUNT(OrderID) AS Orders  FROM df_orders  GROUP BY Shipping_Address  ORDER BY Orders"

df_group = sqldf(query)
df_group.head(10) 

output

厉害了,在Pandas中用<a href='/map/sql/' style='color:#000;font-size:inherit;'>SQL</a>来查询数据,效率超高

数据合并

我们先创建一个数据集,用于后面两个数据集之间的合并,代码如下

query = "SELECT OrderID,
        Quantity, 
        Product_Code, 
        Product_Category, 
        UnitPrice_USD 
        FROM df" df_products = sqldf(query) df_products.head() 

output

厉害了,在Pandas中用<a href='/map/sql/' style='color:#000;font-size:inherit;'>SQL</a>来查询数据,效率超高

我们这里采用的两个数据集之间的交集,因此是INNER JOIN,代码如下

query = "SELECT T1.OrderID, 
        T1.Shipping_Address, 
        T2.Product_Category 
        FROM df_orders T1
        INNER JOIN df_products T2
        ON T1.OrderID = T2.OrderID" df_combined = sqldf(query) df_combined.head() 

output

厉害了,在Pandas中用<a href='/map/sql/' style='color:#000;font-size:inherit;'>SQL</a>来查询数据,效率超高

与LIMIT之间的联用

SQL当中的LIMIT是用于限制查询结果返回的数量的,我们想看查询结果的前10个,代码如下

query = "SELECT OrderID, Quantity, Sales_Manager,  Status, Shipping_Address, 
ShippingCost_USD FROM df LIMIT 10"

df_orders_limit = sqldf(query)
df_orders_limit 

output

厉害了,在Pandas中用<a href='/map/sql/' style='color:#000;font-size:inherit;'>SQL</a>来查询数据,效率超高

数据分析咨询请扫描二维码

最新资讯
更多
客服在线
立即咨询