python pandas query的使用方法

这篇文章主要介绍了python pandas query的使用方法,文章通过围绕主题展开详细的内容介绍,具有一定的参考价值,感兴趣的小伙伴可以参考一下

前言:

Pandas 中应用 query 函数来进行数据筛选。

query 函数的一般用法如下:

df.query('expression')

常用方法:

#!/usr/bin/python import pandas as pd import numpy as np data = {  'brand':['Python',' C ',' C++ ','C#','Java'],  'A':[10,2,5,20,16],  'B':[4,6,8,12,10],  'C':[8,12,18,8,2],  'D':[6,18,14,6,12],  'till years':[4,1,1,30,30]  } df = pd.DataFrame(data=data) print("df数据打印:\n", df, '\n') print('查找数据:\n', df.query('brand == "Python"'), '\n') print('查找数据:\n', df[df['brand'] == "Python"], '\n')

可以使用df.query('brand == "Python"')进行查找,也可以使用df[df['brand'] == "Python"]这种方式进行查找。

out:

df数据打印:
     brand   A   B   C   D  till years
0  Python  10   4   8   6           4
1      C    2   6  12  18           1
2    C++    5   8  18  14           1
3      C#  20  12   8   6          30
4    Java  16  10   2  12          30
 
查找数据:
     brand   A  B  C  D  till years
0  Python  10  4  8  6           4
 
查找数据:
     brand   A  B  C  D  till years
0  Python  10  4  8  6           4
通过数学表达式来筛选:

除了直接通过等于某个值来筛选, query 函数还支持通过数学表达式来进行数据筛选,包括 > 、 <、 + 、 - 、 * 、 / 等。

print('查找数据:\n', df.query('A > 15'), '\n')

out:

查找数据:
   brand   A   B  C   D  till years
3    C#  20  12  8   6          30
4  Java  16  10  2  12          30

通过变量筛选:

在程序比较长的时候,经常会使用变量来作为筛选条件, query 函数在使用变量作为判断标准时,通过在变量前面添加 @ 符号来实现,

示例如下:

name = 'Java' print('查找数据:\n', df.query('brand == @name'), '\n')

out:

查找数据:
   brand   A   B  C   D  till years
4  Java  16  10  2  12          30
通过列表数据筛选:

当需要在某列中筛选多个符合要求的值的时候,可以通过列表( list )来实现,示例如下:

name = ['Python', 'Java'] print('查找数据:\n', df.query('brand in @name'), '\n')

out:

查找数据:
     brand   A   B  C   D  till years
0  Python  10   4  8   6           4
4    Java  16  10  2  12          30

多条件筛选:

  • 两者都需要满足的并列条件使用符号 & , 或单词 and
  • 只需要满足其中之一的条件使用符号 | , 或单词 or
name = ['Python', 'Java'] print('查找数据:\n', df.query('brand in @name & A > 15'), '\n')

out:

查找数据:
   brand   A   B  C   D  till years
4  Java  16  10  2  12          30

列名称中有空格的情况,使用``进行处理:

使用引号处理的话,会报错。

print('查找数据:\n', df.query('`till years` > 10'), '\n')

out:

查找数据:
   brand   A   B  C   D  till years
3    C#  20  12  8   6          30
4  Java  16  10  2  12          30

筛选后选取数据列:

name = ['brand', 'A', 'B', 'till years'] print('查找数据:\n', df.query('`till years` > 10')[name], '\n')

out:

查找数据:
   brand   A   B  till years
3    C#  20  12          30
4  Java  16  10          30

总结:

当用到多条件筛选时,使用query就会显得简洁的多:

print(df[(df['brand'] == 'Python') & (df['A'] == 10) & (df['B'] == 4)]) print(df.query('brand == "Python" & A == 10 & B == 4'))

到此这篇关于python pandas query的使用方法的文章就介绍到这了,更多相关python pandas query 内容请搜索0133技术站以前的文章或继续浏览下面的相关文章希望大家以后多多支持0133技术站!

以上就是python pandas query的使用方法的详细内容,更多请关注0133技术站其它相关文章!

赞(0) 打赏
未经允许不得转载:0133技术站首页 » python