新聞中心
本篇文章帶大家聊聊一個python Pandas庫的使用小技巧,介紹一下使用query()優(yōu)雅查詢的方法,希望對大家有所幫助!

成都創(chuàng)新互聯(lián)公司主營喀喇沁網(wǎng)站建設(shè)的網(wǎng)絡(luò)公司,主營網(wǎng)站建設(shè)方案,重慶APP開發(fā)公司,喀喇沁h5成都小程序開發(fā)搭建,喀喇沁網(wǎng)站營銷推廣歡迎喀喇沁等地區(qū)企業(yè)咨詢
對于 Pandas 根據(jù)條件獲取指定數(shù)據(jù),相信大家都能夠輕松的寫出相應(yīng)代碼,但是如果你還沒用過 query,相信你會被它的簡潔所折服!
先創(chuàng)建一個 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)})
我們現(xiàn)在選取 A列字母出現(xiàn)在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() 來實現(xiàn)。
>>> 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 后的代碼簡潔易懂,并且它對于內(nèi)存的消耗也更小。
多條件查詢
選取 A列字母出現(xiàn)在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列字母出現(xiàn)在B列,并且索引大于2 的所有行。
>>> df.query('A in B and index > 2')
A B C D E.E
3 b d 6 4 7
多索引選取
創(chuàng)建一個兩層索引的 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 9
2、當有多層索引無名時,通過索引級別來選取。
>>> 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() 用法比較簡單,可以快速上手,代碼可讀性也提高了不少。
新聞標題:一文了解Python中如何使用query()進行優(yōu)雅的查詢
分享地址:http://www.dlmjj.cn/article/dpijeei.html


咨詢
建站咨詢
