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
通过数学表达式来筛选:
- 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
- name = 'Java'
- print('查找数据:\n', df.query('brand == @name'), '\n')
-
- out:
- 查找数据:
- brand A B C D till years
- 4 Java 16 10 2 12 30
通过列表数据筛选:
- 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
多条件筛选:
- 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'))
-