python pandas query

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

python pandas query

soulsoul_god   2022-09-29 我要评论

前言:

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'))

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们