日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學無先后,達者為師

網站首頁 編程語言 正文

Pandas使用query()優雅的查詢實例_python

作者:Dream丶Killer ? 更新時間: 2022-04-06 編程語言

對于 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 ?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() 用法比較簡單,可以快速上手,代碼可讀性也提高了不少。

原文鏈接:https://juejin.cn/post/7055974103127162911

欄目分類
最近更新