由于工作关系 , 经常会用到sql和python的pandas模块,两者有很多相似之处,我将整理出系列的对比文章,并保持更新. 若有不尽之处,敬请指出.
官方文档地址:https://pandas.pydata.org/docs/getting_started/comparison/comparison_with_sql.html
文章目录
1. 基础说明
本文代码环境基于windows 10 和 anaconda3创建的.python3.6虚拟环境
- 下表的名字,在sql中数据叫table, 在pandas中叫df, 在一般的df中
id
这个字符是不显示的,在df中,这列叫做index
id | colA | colB | colC | colD |
---|---|---|---|---|
0 | A | X | 100 | 90 |
1 | A | 50 | 60 | |
2 | B | Ya | 30 | 60 |
3 | C | Yb | 50 | 80 |
4 | A | Xa | 20 | 50 |
生成上表的语句是:
df = pd.DataFrame({'colA' : list('AABCA'), 'colB' : ['X',np.nan,'Ya','Xb','Xa'],'colC' : [100,50,30,50,20], 'colD': [90,60,60,80,50]})
2. select 操作
等效说明
sql操作(table)为数据表名 | pandas操作(df)为DataFrame框架数据 | 说明 |
---|---|---|
select * from table |
df |
|
select colA,colB from table |
df.loc[:,['colA', 'colB']] 或df[['colA', 'colB']] |
关键字: loc |
脚注1. | ||
1: 2018-08-09 新增df[['colA', 'colB']] 方法 |
3. where操作
sql操作(table)为数据表名 | pandas操作(df)为DataFrame框架数据 | 说明 |
---|---|---|
select * from table where colA = 'B' |
df[df['colA']=='B'] |
在DF中使用== 表示两者比较关系 |
select * from table where colA = 'A' and colC = 50 |
df[(df['colA']=='A') & (df['colC'] == 50)] |
and操作用& 符号,且& 前后的语句需用() 括起来 |
select colA, colC from table where colA='A' and colC=50 |
df=[['colA', 'colC']]; df2=df[(df['colA']=='A') & (df['colC'] == 50)] |
需要进行两次赋值操作 |
select colA from table where colC>50 |
df = df.loc[df["colc"]>50, "colA"] |
这个操作比较6 |
select * from table where colB is not null |
df[df['colB'].notna()] |
关键词 isna() 与 notna() 两个方法。 |
4. in操作
sql操作(table)为数据表名 | pandas操作(df)为DataFrame框架数据 | 说明 |
---|---|---|
select * from table where colA in ('A','B') |
df[df['colA'].isin(['A','B'])] |
关键字:isin |
select * from table where colA not in ('A','B') |
df[~df['colA'].isin(['A','B'])] |
关键字:~ 取反 |
5. regexp正则操作
因markdown使用不熟, 下表中的{竖线}
应替换为:|
sql操作(table)为数据表名 | pandas操作(df)为DataFrame框架数据 | 说明 |
---|---|---|
select * from table where colB regexp 'a{竖线}b' |
df[df['colB'].str.contains('a{竖线}b')] |
关键字:str.contains |
select * from table where colB not regexp 'a{竖线}b' |
df[~df['colB'].str.contains('a{竖线}b')] |
关键字:~ 取反 |
6. group by操作
单独group by 没有意义 ,一般会和其它应用组合起来使用, 比如sql中的AVG(), COUNT(), SUM(), MAX()等函数,以后的工作中有更多的groupby操作,将会持续更新到这里.可以参考 我的另一文章
sql操作(table)为数据表名 | pandas操作(df)为DataFrame框架数据 | 说明 |
---|---|---|
select colA, sum(colC) from table group by colA |
df.groupby(['colA'])['colC'].sum().reset_index() |
关键字:reset_index() 的作用是将groupby后的index进行重置,以保持数据的二维表结构, |
select colA, count(colC) from table group by colA |
df.groupby(['colA'])["colC"].count().reset_index() |
关键字:count() ,作用是计数, 同值会重复计数, |
select colA, count(distinct colC) from table group by colA |
df.groupby(['colA']).agg({"colc": pd.Series.nunique}) |