Python pandas库 -> 和SQL查询的一些等价操作

用pandas可以更灵活的实现SQL的很多功能

下面是一些SQL常用语句在pandas里面的对应写法

 1 import numpy as np
 2 import pandas as pd
 3 from pandas import DataFrame,Series
 4 
 5 df1=DataFrame(np.arange(20).reshape(5,4),columns=list('abcd'),index=list('efghi'))
 6 
 7 print('我是df1:\n{}'.format(df1))
 8 print('select等价操作:\n{}'.format(df1.loc[:,['a','b']])) #用loc函数实现选择字段 也可以用赋值的方式直接改变数据
 9 print('where等价操作:\n{}'.format(df1[(df1['a']>=12) & -(df1['b']<17)])) #这里相当于where a>=12 and not b<17
10 print('in等价操作:\n{}'.format(df1[df1['a'].isin([0,4])]))
11 print('not in等价操作:\n{}'.format(df1[-df1['a'].isin([0,4])])) #多了一个负号,代表not
12 print('order by等价操作:\n{}'.format(df1.sort_values('a',ascending=False))) #用sort_values实现排序,这里是降序
13 print('as等价操作:\n{}'.format(df1.rename(columns={'a':'new_a'},inplace=False))) #rename加字典映射实现as
14 
15 df2=DataFrame({'x':[0,4,1,2,3,4],'y':list('python')})
16 
17 print('我是df2:\n{}'.format(df2))
18 print('join等价操作:\n{}'.format(pd.merge(df1,df2,left_on='a',right_on='x',how='left'))) #可以实现各种join功能
19 
20 df1.loc['j',:]=[0,1,3,4] #给df1增加一行数据
21 
22 print('我是新的df1:\n{}'.format(df1))
23 print('distinct等价操作:\n{}'.format(df1.drop_duplicates(subset=['a','b']))) #针对部分字段进行去重,比SQL更加灵活

 

SQL where操作的逻辑运算符not and or

分别对应pandas的 -  & 和 |

谢谢!

posted @ 2019-05-30 16:16  布里塔  阅读(544)  评论(0编辑  收藏  举报