欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Pandas使用query()優(yōu)雅的查詢實(shí)例

 更新時(shí)間:2022年01月24日 16:44:38   作者:Dream丶Killer  
本文主要介紹了Pandas使用query()優(yōu)雅的查詢實(shí)例,文中通過(guò)示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下

對(duì)于 Pandas 根據(jù)條件獲取指定數(shù)據(jù),相信大家都能夠輕松的寫(xiě)出相應(yīng)代碼,但是如果你還沒(méi)用過(guò) query,相信你會(huì)被它的簡(jiǎn)潔所折服!

常規(guī)用法

先創(chuàng)建一個(gè) 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列 的所有行。先看兩種常見(jiàn)寫(xiě)法。

>>> 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() 來(lái)實(shí)現(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 后的代碼簡(jiǎn)潔易懂,并且它對(duì)于內(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 也可以用 & 表示。

引用變量

表達(dá)式中也可以使用外部定義的變量,在變量名前用@標(biāo)明。

>>> 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)建一個(gè)兩層索引的 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.當(dāng)有多層索引有名稱時(shí),通過(guò)索引名稱直接選取。

>>> df.query("color == 'red'")
? ? ? ? ? ? A ?B
color rank ? ? ?
red ? 3 ? ? 6 ?7
? ? ? 4 ? ? 8 ?9

2.當(dāng)有多層索引無(wú)名時(shí),通過(guò)索引級(jí)別來(lái)選取。

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

特殊字符

對(duì)于列名中間有空格或運(yùn)算符等其他特殊符號(hào),需要使用反引號(hào) ``。

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

總的來(lái)說(shuō),query() 用法比較簡(jiǎn)單,可以快速上手,代碼可讀性也提高了不少。

到此這篇關(guān)于Pandas使用query()優(yōu)雅的查詢實(shí)例的文章就介紹到這了,更多相關(guān)Pandas query()查詢內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

您可能感興趣的文章:

相關(guān)文章

最新評(píng)論