python数据分析——python类似sql用法(四)

版权声明:欢迎转载,知识无界注明出处即可 https://blog.csdn.net/Arwen_H/article/details/81612106

——python sql
pandas在数据处理上有着丰富且高效的函数,我们把数据清理、整理好后,只是一张原始的DataFrame。python也能像SQL一样或者excel里面的voolkup一样将数据进行合并,也能像excel里面的透视表或者sql group by一样进行数据透视组合,也能像excel的查找功能或者sql里面的where功能进行数据筛选。

python类似sql where用法或excel查找用法

python 类似where用法中的 col=a、col<>a、col=a and col =b、col=a or col=b、col in(a,b,c)、col not in(a,b,c)

语法 描述
df[‘col’]==‘Female’ 查找df表col列中内容等于Female的内容=用法
df[‘col’]!=11 查找df表col列中内容不等于11的内容<>用法
df[df[‘col’]==‘Female’] 查找df表中col列单个条件等于Female的内容,并返回整张表所有列
df[(df[‘col’]==‘Female’)&(df[‘col2’]>0)] 查找df表中col列等于Female,并且col2列大于0的内容,返回整张表所有列 and用法
df[(df[‘col’]>=10)|(df[‘col2’]<50)] 查找df表中col列小于等于10或者col2列小于50的内容,返回整张表所有列 or用法
df[df[‘col’].isin([21.01, 23.68, 24.59])] 查找col列中包含指定值的内容,返回整张表所有列in用法
df[-df[‘col’].isin([11,63])] 查找col列中不包含多个值的内容,返回整张表not in用法

代码案例

import pandas as pd
data={'a':[1,2,3,4,3,2,6],
      'b':[43,23,52,23,11,63,83],
      'c':['true','fales','true','true','fales','fales','true']}
data=pd.DataFrame(data)#创建一个df表
Out[33]: 
   a   b      c
0  1  43   true
1  2  23  fales
2  3  52   true
3  4  23   true
4  3  11  fales
5  2  63  fales
6  6  83   true
#查找b列内容大于等于30的所有列
data[data['b']>=30] 
Out[34]: 
   a   b      c
0  1  43   true
2  3  52   true
5  2  63  fales
6  6  83   true
 #查找b类大于等于30并且a列小于5的所有列
data[(data['b']>=30)&(data['a']<5)]
Out[35]: 
   a   b      c
0  1  43   true
2  3  52   true
5  2  63  fales
#查找b列不包含11和63的所有列,不用`-`号代表包含
data[-data['b'].isin([11,63])]
Out[36]: 
   a   b      c
0  1  43   true
1  2  23  fales
2  3  52   true
3  4  23   true
6  6  83   true

python类似sql Group by分组用法

group一般会配合合计函数(Aggregate functions)使用,比如:count、avg等。Pandas对合计函数的支持有限,有count和size函数实现SQL的count

语法 描述
df.groupby(‘sex’).size() 对字段sex单列进行分组,只展示sex字段计数
df.groupby(‘sex’)[‘tip’].count() 对字段sex单列进行分组,计算tip字段计数
df.groupby(‘sex’).count() 根据字段sex单列进行分组计算,展示所有字段计数
df.groupby(‘sex’).agg({‘tip’:np.max,‘total_bill’:np.sum}) 根据字段sex进行分组,分别求tip最大值,字段total_bill求和值
df.groupby(‘tip’).agg({‘sex’: pd.Series.nunique}) 去重tip字段并依sex字段进行计数

python中的group也支持迭代常用于循环对整个df进行分组然后再进行加工

语法 描述
for x in df.groupby(‘col’): 循环语句对df表按col列进行分组,返回多个tuple,x[1]选取返回的df数据
for x in df.groupby([‘col’,‘col2’]): 循环语句对df表按col、col2列进行分组,返回多个tuple,x[1]选取返回的df数据

代码案例

  • 直接groupby计算
#按c列分组分别计算a,b列的和
data.groupby('c').sum() 

Out[37]: 
        a    b
c             
fales   7   97
true   14  201

#按c列分组只求a列的和
data.groupby('c')['a'].sum()
Out[38]: 
c
fales     7
true     14
  • for循环groupby迭代
#将data按c列分组,重新生成两个单独的df
for x in data.groupby('c'):
    print(x[1])

Out[40]:
   a   b      c
1  2  23  fales
4  3  11  fales
5  2  63  fales
   a   b     c
0  1  43  true
2  3  52  true
3  4  23  true
6  6  83  true

python类似sql join关联用法

语法 描述
pd.merge(a,b,how=‘left’,left_on=‘sex’,right_on=‘sex’) on指定的列做join Pandas满足left、right、inner、outer四种join方
pd.merge(a,b,how=‘left’,on=[‘a1’,‘b1’,‘c1’]) on=指定需要相同的多列,至少三列列进行join同时满足匹配
pd.merge(a,b,left_index=True,right_index=True) 根据索引进行合并left_index or right_index,解决一对多boolean类型

代码案例

data1={'d':[7,44,1,44,31,42,3],
      'b':[43,23,52,23,11,63,83],
      'c':['true','fales','true','true','fales','fales','true']}
data1=pd.DataFrame(data1)#再创一个表命名为data1,data表在最前面

Out[52]: 
    d   b      c
0   7  43   true
1  44  23  fales
2   1  52   true
3  44  23   true
4  31  11  fales
5  42  63  fales
6   3  83   true
pd.merge(data,data1,how='inner',left_on='a',right_on='d')
#取data表a列与data1表d列相同的交集部分
Out[55]: 
   a  b_x    c_x  d  b_y   c_y
0  1   43   true  1   52  true
1  3   52   true  3   83  true
2  3   11  fales  3   83  true

python类似sql order排序用法

语法 描述
df.sort_values([‘col’], ascending=[False]) 按col列排序,ascending=False为降序
df.sort_values([‘col’], ascending=[True]) 按col列排序,ascending=True为升序

代码案例

data.sort_values(['a'],ascending=[True])对a列进行排序

Out[56]: 
   a   b      c
0  1  43   true
1  2  23  fales
5  2  63  fales
2  3  52   true
4  3  11  fales
3  4  23   true
6  6  83   true

python类似sql Distinct去重用法

语法 描述
df.drop_duplicates(subset=[‘col’], keep=‘first’, inplace=True) 根据某列对dataframe进行去重

包含参数

参数 描述
subset 为选定的列做distinct,默认为所有列
keep 值选项{‘first’, ‘last’, False},保留重复元素中的第一个、最后一个,或全部删除
inplace 默认为False,返回一个新的dataframe;若为True,则返回去重后的原dataframe

代码案例

data.drop_duplicates(subset=['a'],keep='first',inplace=True)
#将data表a列中重复的去掉,并替换原表
Out[59]: 
   a   b      c
0  1  43   true
1  2  23  fales
2  3  52   true
3  4  23   true
6  6  83   true

猜你喜欢

转载自blog.csdn.net/Arwen_H/article/details/81612106