Pandas_Select_Data_query()

Pandas_Select_Data_query()

查询数据除了[ ]、loc、iloc、where外,还有另外一个简洁高效的查询方法——query()。

了解了一下相关操作,简直惊呆了,完全就是英语白话,容易掌握,语句也短,称为短小精悍一点儿都不为过。

学了之后,再也不用写辣么长的查询语句了。

本文就简单介绍一下query()方法的相关操作。

import pandas as pd
import numpy as np
​
data = pd.DataFrame(np.random.randn(5,4), columns=list('abcd'))
data

out:
    a   b   c   d
0   -0.055029   1.376917    -0.228314   1.595987
1   -0.259330   -0.114194   1.252481    0.386451
2   0.873330    -1.279337   2.390891    -0.044016
3   -1.190554   -1.359401   -0.191798   1.742165
4   -0.750102   0.143094    0.742452    -1.577230

pandas一般做法

data[(data.a < data.b) & (data.c > data.d)]

out:
    a   b   c   d
1   -0.259330   -0.114194   1.252481    0.386451
4   -0.750102   0.143094    0.742452    -1.577230
data.loc[(data.a < data.b) & (data.c > data.d)]

out:
    a   b   c   d
1   -0.259330   -0.114194   1.252481    0.386451
4   -0.750102   0.143094    0.742452    -1.577230

使用query()

data.query('(a < b) and (c > d)')

out:
    a   b   c   d
1   -0.259330   -0.114194   1.252481    0.386451
4   -0.750102   0.143094    0.742452    -1.577230
data.query('a < b < c')

out:
    a   b   c   d
1   -0.259330   -0.114194   1.252481    0.386451
4   -0.750102   0.143094    0.742452    -1.577230

query()可以使用索引

直接使用'index':

data.query('index > 2')

out:
    a   b   c   d
i               
3   -1.190554   -1.359401   -0.191798   1.742165
4   -0.750102   0.143094    0.742452    -1.577230

也可以先命名仔使用:

data.index.name= 'i'
data.query('i > 2')

out:
    a   b   c   d
i               
3   -1.190554   -1.359401   -0.191798   1.742165
4   -0.750102   0.143094    0.742452    -1.577230

如果索引的名称与列名称重叠,则列名称优先。

data.index.name= 'a'
data.query('a > .5')

out:
    a   b   c   d
a               
2   0.87333 -1.279337   2.390891    -0.044016

MultiIndex query()语法

companies = np.random.choice(['apple', 'huawei'], size = 6)
products = np.random.choice(['mobile', 'pad'], size = 6)
companies

out:
array(['apple', 'apple', 'huawei', 'huawei', 'huawei', 'huawei'],
      dtype='<U6')
products

out:
array(['pad', 'mobile', 'mobile', 'mobile', 'pad', 'pad'], dtype='<U6')
index = pd.MultiIndex.from_arrays([companies, products], names=['company', 'product'])
data_mul = pd.DataFrame(np.random.randn(6, 3), index=index)
data_mul

out:
                0   1   2
company product         
apple   pad -0.968198   -0.619911   1.134541
        mobile  -0.608740   -0.909656   -0.027498
huawei  mobile  1.016521    1.882203    -1.001023
        mobile  0.841595    0.065712    1.732188
        pad 0.540195    -0.762794   0.549758
        pad -2.613445   -0.387707   -0.780770
data_mul.query('product == "mobile"')


out:
                0   1   2
company product         
apple   mobile  -0.608740   -0.909656   -0.027498
huawei  mobile  1.016521    1.882203    -1.001023
        mobile  0.841595    0.065712    1.732188
data_mul.query('company == "huawei"')

out:
                0   1   2
company product         
huawei  mobile  1.016521    1.882203    -1.001023
        mobile  0.841595    0.065712    1.732188
        pad 0.540195    -0.762794   0.549758
        pad -2.613445   -0.387707   -0.780770

如果MultiIndex未命名的级别,您可以使用特殊名称引用它们:

data_mul.index.names = [None, None]
data_mul.query('ilevel_0 == "huawei"')

out:
                0   1   2
huawei  mobile  1.016521    1.882203    -1.001023
        mobile  0.841595    0.065712    1.732188
        pad 0.540195    -0.762794   0.549758
        pad -2.613445   -0.387707   -0.780770
data_mul.query('ilevel_1 == "pad"')

out:
            0   1   2
apple   pad -0.968198   -0.619911   1.134541
huawei  pad 0.540195    -0.762794   0.549758
        pad -2.613445   -0.387707   -0.780770

query()与pandas语法比较

  • 完全类似numpy的语法;
  • 可以直接删除括号;
  • 使用英语而不是符号;
  • 最大程度接近自然语言。

有括号

data.query('(a < b) and (c > d)')

out:
    a   b   c   d
a               
1   -0.259330   -0.114194   1.252481    0.386451
4   -0.750102   0.143094    0.742452    -1.577230

无括号

data.query('a < b and c > d')

out:
    a   b   c   d
a               
1   -0.259330   -0.114194   1.252481    0.386451
4   -0.750102   0.143094    0.742452    -1.577230

使用符号

data.query('a < b & c > d')

out:
    a   b   c   d
a               
1   -0.259330   -0.114194   1.252481    0.386451
4   -0.750102   0.143094    0.742452    -1.577230

使用英语

data.query('a < b or c > d')

out:
    a   b   c   d
a               
0   -0.055029   1.376917    -0.228314   1.595987
1   -0.259330   -0.114194   1.252481    0.386451
2   0.873330    -1.279337   2.390891    -0.044016
4   -0.750102   0.143094    0.742452    -1.577230

接近自然语言

data.query('a < b < c')

out:
    a   b   c   d
a               
1   -0.259330   -0.114194   1.252481    0.386451
4   -0.750102   0.143094    0.742452    -1.577230

使用 in 与 not in 操作符

df = pd.DataFrame({'a': list('aabbccddeeff'), 'b': list('aaaabbbbcccc'),
                   'c': np.random.randint(5, size=12),
                   'd': np.random.randint(9, size=12)})
df

out:
    a   b   c   d
0   a   a   3   8
1   a   a   2   6
2   b   a   4   6
3   b   a   4   8
4   c   b   2   7
5   c   b   3   3
6   d   b   4   1
7   d   b   1   1
8   e   c   4   6
9   e   c   4   3
10  f   c   2   5
11  f   c   0   0

in

df.query('a in b')

out:
    a   b   c   d
0   a   a   3   8
1   a   a   2   6
2   b   a   4   6
3   b   a   4   8
4   c   b   2   7
5   c   b   3   3

一般方法

df[df.a.isin(df.b)]

out:
    a   b   c   d
0   a   a   3   8
1   a   a   2   6
2   b   a   4   6
3   b   a   4   8
4   c   b   2   7
5   c   b   3   3

not in

df.query('a not in b')

out: 
    a   b   c   d
6   d   b   4   1
7   d   b   1   1
8   e   c   4   6
9   e   c   4   3
10  f   c   2   5
11  f   c   0   0

一般方法:

df[~df.a.isin(df.b)]

out:
    a   b   c   d
6   d   b   4   1
7   d   b   1   1
8   e   c   4   6
9   e   c   4   3
10  f   c   2   5
11  f   c   0   0

与其他表达式结合

df.query('a in b and c < d')

out:
    a   b   c   d
0   a   a   3   8
1   a   a   2   6
2   b   a   4   6
3   b   a   4   8
4   c   b   2   7

一般方法:

df[(df.a.isin(df.b)) & (df.c < df.d)]

out:
    a   b   c   d
0   a   a   3   8
1   a   a   2   6
2   b   a   4   6
3   b   a   4   8
4   c   b   2   7

== 运算符与list的特殊用法

==、!=相当于in 、not in。

== 运算符

df.query('a == ["a", "b", "c"]')

out:
    a   b   c   d
0   a   a   3   8
1   a   a   2   6
2   b   a   4   6
3   b   a   4   8
4   c   b   2   7
5   c   b   3   3
df.query('a in ["a", "b", "c"]')

out:
    a   b   c   d
0   a   a   3   8
1   a   a   2   6
2   b   a   4   6
3   b   a   4   8
4   c   b   2   7
5   c   b   3   3

!= 运算符

df.query('a != ["a", "b", "c"]')

out:
    a   b   c   d
6   d   b   4   1
7   d   b   1   1
8   e   c   4   6
9   e   c   4   3
10  f   c   2   5
11  f   c   0   0
df.query('a not in ["a", "b", "c"]')

out:
    a   b   c   d
6   d   b   4   1
7   d   b   1   1
8   e   c   4   6
9   e   c   4   3
10  f   c   2   5
11  f   c   0   0

布尔运算符

可以使用单词not或~运算符否定布尔表达式。

df['bools'] = df.d > df.d.mean()
df.query('bools')

out:
    a   b   c   d   bools
0   a   a   3   8   True
1   a   a   2   6   True
2   b   a   4   6   True
3   b   a   4   8   True
4   c   b   2   7   True
8   e   c   4   6   True
10  f   c   2   5   True
df.query('d > d.mean()')

out:
    a   b   c   d   bools
0   a   a   3   8   True
1   a   a   2   6   True
2   b   a   4   6   True
3   b   a   4   8   True
4   c   b   2   7   True
8   e   c   4   6   True
10  f   c   2   5   True
df.query('not bools')

out:
    a   b   c   d   bools
5   c   b   3   3   False
6   d   b   4   1   False
7   d   b   1   1   False
9   e   c   4   3   False
11  f   c   0   0   False
df.query('~bools')

out:
    a   b   c   d   bools
5   c   b   3   3   False
6   d   b   4   1   False
7   d   b   1   1   False
9   e   c   4   3   False
11  f   c   0   0   False
​
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 160,706评论 4 366
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 68,002评论 1 301
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 110,462评论 0 250
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 44,375评论 0 216
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,763评论 3 294
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,849评论 1 224
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 32,033评论 2 317
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,768评论 0 204
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,490评论 1 246
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,734评论 2 253
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 32,204评论 1 264
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,566评论 3 260
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 33,227评论 3 241
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,137评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,934评论 0 201
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,926评论 2 283
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,774评论 2 274

推荐阅读更多精彩内容