SQLite | SQLite 与 Pandas 比较篇之一

1. SQLite 与 Pandas 异同点比较

1.1 数据导入

1.1.1 SQLIte

SQLite 需要首先导入数据库文件并使用 select 语句选取记录:

  • 使用Jupyter Notebook 运行 SQL 语句需安装 ipython-sql

  • %sql 以及 %%sql 为在 Notebook 中运行 SQL 语句,在 SQLite 命令行或 SQLite Stiduo 中不需要 %sql 或 %%sql

%load_ext sql
%sql sqlite:///DataBase/weather_stations.db
'Connected: @DataBase/weather_stations.db'
%%sql
select * from station_data
limit 0,3
 * sqlite:///DataBase/weather_stations.db
Done.
station_numberreport_codeyearmonthdaydew_pointstation_pressurevisibilitywind_speedtemperatureprecipitationsnow_depthfograinhailthundertornado
14308034DDA72002122133.8987.43.40.2360None11111
76644039537B199810172.71014.65.96.783.30None00000
176010C3C6D5200151855.7None7.34.369.10None00000

1.1.2 Pandas

在 Python 中我们可以利用 sqlite3 模块来读取数据库并转换为 Pandas 的 DataFrame 格式:

import sqlite3
import pandas as pd
con = sqlite3.connect('./DataBase/weather_stations.db')
cursor = con.execute('select * from station_data')
rows = cursor.fetchall()
df = pd.DataFrame(rows, columns=[x[0] for x in cursor.description])
df.head(3)
station_numberreport_codeyearmonthdaydew_pointstation_pressurevisibilitywind_speedtemperatureprecipitationsnow_depthfograinhailthundertornado
014308034DDA72002122133.8987.43.40.236.00.0NaN11111
176644039537B199810172.71014.65.96.783.30.0NaN00000
2176010C3C6D5200151855.7NaN7.34.369.10.0NaN00000

1.2 选取数据

1.2.1 SQLite

在 SQLite 中,我们需要通过 select 语句来筛选数据,并可以使用 alias、内置函数和文字拼接等对数据进行处理:

%%sql
select
station_number ||'_'|| report_code as number, -- 将两个拼接
round(temperature*9/5+32, 2) as Fahrenheit -- 将摄氏度转换为华氏度
from station_data
limit 0,3
 * sqlite:///DataBase/weather_stations.db
Done.
numberFahrenheit
143080_34DDA796.0
766440_39537B181.94
176010_C3C6D5156.38

1.2.2 Pandas

Pandas 中似乎没有直接作用于字符的拼接函数,因此需要多一步转换的过程才能得到与 SQL 中 concat 相同的效果:

pd.concat( [pd.Series([str(num)+'_'+code for (num,code) in 
                       zip(list(df['station_number']), 
                           list(df['report_code']))], name='number'), 
            pd.Series(round(df['temperature']*9/5+32, 2), name='Fahrenheit')],
          axis=1).head(3)
numberFahrenheit
0143080_34DDA796.80
1766440_39537B181.94
2176010_C3C6D5156.38

1.3 筛选数据

1.3.1 SQLite

SQLite 中使用 where 对数据进行筛选,如筛选 2005 年至 2010 年的数据:

%%sql
select * from station_data
where year>=2005 and year<=2010
limit 0,3
 * sqlite:///DataBase/weather_stations.db
Done.
station_numberreport_codeyearmonthdaydew_pointstation_pressurevisibilitywind_speedtemperatureprecipitationsnow_depthfograinhailthundertornado
1256001451502007101433None6.92.539.70None00000
598550C5C66E2006101572.9None14.21.7820None00000
941830229317200741966.5994.9None476.30None00000

筛选月份为 3、6、9、12 的数据:

%%sql 
select * from station_data 
where Month in (3,6,9,12)
limit 0,3;
 * sqlite:///DataBase/weather_stations.db
Done.
station_numberreport_codeyearmonthdaydew_pointstation_pressurevisibilitywind_speedtemperatureprecipitationsnow_depthfograinhailthundertornado
14308034DDA72002122133.8987.43.40.2360None11111
8219301F8A7B195361872.81007.112.43.681.30None00000
478070D028D8198162773.4None7.93771.93None00000

1.3.2 Pandas

筛选 2005 年至 2010 年的数据:

df[(df['year']>=2005) & (df['year']<=2010)].head(3)
station_numberreport_codeyearmonthdaydew_pointstation_pressurevisibilitywind_speedtemperatureprecipitationsnow_depthfograinhailthundertornado
31256001451502007101433.0NaN6.92.539.70.0NaN00000
9598550C5C66E2006101572.9NaN14.21.782.00.0NaN00000
18941830229317200741966.5994.9NaN4.076.30.0NaN00000

筛选月份为 3、6、9、12 的数据:

df[ [ [data in [3,6,9,12]] for data in df['month'].values ] ].head(3)
station_numberreport_codeyearmonthdaydew_pointstation_pressurevisibilitywind_speedtemperatureprecipitationsnow_depthfograinhailthundertornado
014308034DDA72002122133.8987.43.40.236.00.00NaN11111
58219301F8A7B195361872.81007.112.43.681.30.00NaN00000
6478070D028D8198162773.4NaN7.93.077.01.93NaN00000

1.4 数据聚合与分组

1.4.1 SQLite

在 SQLite 中,我们使用 group by 和内置聚合函数实现聚合分组操作,如统计每个月龙卷风的记录次数:

%%sql
select year, month,
count(*) as record_count
from station_data
where tornado == 1
group by year, month
order by year, month
limit 0,5;
 * sqlite:///DataBase/weather_stations.db
Done.
yearmonthrecord_count
193773
194183
1942103
194313
194343

1.4.2 Pandas

同样在 Pandas 中,也有 groupby 函数实现分组操作:

df[df['tornado']==1].groupby(['year','month'])['tornado'].count().head(5)
year  month
1937  7        3
1941  8        3
1942  10       3
1943  1        3
      4        3
Name: tornado, dtype: int64

2. 总结

从数据导入、选取、筛选、聚合与分组可以看出, SQLite 具有结构化的特点,
容易操作且易上手,代码一目了然。反观 Pandas ,则继承了 Pythonic 的特点。
虽然部分功能需要自己写循环,但由于列表推倒式的存在,使得这代码依然可以保持短小精悍。
总体而言,SQLite 的功能实现更加方便快捷,而 Pandas 则拥有更高的自由度,
但需要对 Python 比较熟悉,两者各有千秋!

相关文章:

SQL | 目录
SQLite | Select 语句
SQLite | Where 子句
SQLite | Group by 与 Order by 子句
SQLite | CASE 子句
SQLite | Join 语句
SQLite | 数据库设计与 Creat Table 语句
SQLite | Insert、Delete、Updata 与 Drop 语句

  • 3
    点赞
  • 18
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值