Pandas使用query()优雅的查询实例
目录
- 常规用法
- 多条件查询
- 引用变量
- 索引选取
- 多索引选取
- 特殊字符
对于 pandas 根据条件获取指定数据,相信大家都能够轻松的写出相应代码,但是如果你还没用过 query,相信你会被它的简洁所折服!
常规用法
先创建一个 dataframe。
import pandas as pd
df = pd.dataframe(
{'a': ['e', 'd', 'c', 'b', 'a'],
'b': ['f', 'b', 'c', 'd', 'e'],
'c': range(0, 10, 2),
'd': range(10, 0, -2),
'e.e': range(10, 5, -1)})我们现在选取 a列字母出现在b列 的所有行。先看两种常见写法。
>>> df[df['a'].isin(df['b'])] a b c d e.e 0 e f 0 10 10 1 d b 2 8 9 2 c c 4 6 8 3 b d 6 4 7 >>> df.loc[df['a'].isin(df['b'])] a b c d e.e 0 e f 0 10 10 1 d b 2 8 9 2 c c 4 6 8 3 b d 6 4 7
下面使用 query() 来实现。
>>> df.query("a in b")
a b c d e.e
0 e f 0 10 10
1 d b 2 8 9
2 c c 4 6 8
3 b d 6 4 7可以看到使用 query 后的代码简洁易懂,并且它对于内存的消耗也更小。
多条件查询
选取 a列字母出现在b列,并且c列小于d列 的所有行。
>>> df.query('a in b and c < d')
a b c d e.e
0 e f 0 10 10
1 d b 2 8 9
2 c c 4 6 8这里 and 也可以用 & 表示。
引用变量
表达式中也可以使用外部定义的变量,在变量名前用@标明。
>>> number = 5
>>> df.query('a in b & c > @number')
a b c d e.e
3 b d 6 4 7索引选取
选取 a列字母出现在b列,并且索引大于2 的所有行。
>>> df.query('a in b and index > 2')
a b c d e.e
3 b d 6 4 7多索引选取
创建一个两层索引的 dataframe。
>>> import numpy as np >>> colors = ['yellow']*3 + ['red']*2 >>> rank = [str(i) for i in range(5)] >>> index = pd.multiindex.from_arrays([colors, rank], names=['color', 'rank']) >>> df = pd.dataframe(np.arange(10).reshape(5, 2),columns=['a', 'b'] , index=index) >>> df = pd.dataframe(np.arange(10).reshape(5, 2),columns=['a', 'b'] , index=index) >>> df a b color rank yellow 0 0 1 1 2 3 2 4 5 red 3 6 7 4 8 9
1.当有多层索引有名称时,通过索引名称直接选取。
>>> df.query("color == 'red'")
a b
color rank
red 3 6 7
4 8 92.当有多层索引无名时,通过索引级别来选取。
>>> df.index.names = [none, none]
>>> df.query("ilevel_0 == 'red'")
a b
red 3 6 7
4 8 9
>>> df.query("ilevel_1 == '4'")
a b
red 4 8 9特殊字符
对于列名中间有空格或运算符等其他特殊符号,需要使用反引号 ``。
>>> df.query('a == b | (c + 2 > `e.e`)')
a b c d e.e
2 c c 4 6 8
3 b d 6 4 7
4 a e 8 2 6总的来说,query() 用法比较简单,可以快速上手,代码可读性也提高了不少。
到此这篇关于pandas使用query()优雅的查询实例的文章就介绍到这了,更多相关pandas query()查询内容请搜索萬仟网以前的文章或继续浏览下面的相关文章希望大家以后多多支持萬仟网!
看完文章,还可以扫描下面的二维码下载快手极速版领4元红包
除了扫码领红包之外,大家还可以在快手极速版做签到,看视频,做任务,参与抽奖,邀请好友赚钱)。
邀请两个好友奖最高196元,如下图所示:







