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

學無先后,達者為師

網站首頁 編程語言 正文

python?pandas?query的使用方法_python

作者:soulsoul_god ? 更新時間: 2022-11-05 編程語言

前言:

Pandas 中應用 query 函數來進行數據篩選。

query 函數的一般用法如下:

df.query('expression')

常用方法:

#!/usr/bin/python
import pandas as pd
import numpy as np
data = {
?'brand':['Python',' C ',' C++ ','C#','Java'],
?'A':[10,2,5,20,16],
?'B':[4,6,8,12,10],
?'C':[8,12,18,8,2],
?'D':[6,18,14,6,12],
?'till years':[4,1,1,30,30]
?}
df = pd.DataFrame(data=data)
print("df數據打印:\n", df, '\n')

print('查找數據:\n', df.query('brand == "Python"'), '\n')
print('查找數據:\n', df[df['brand'] == "Python"], '\n')

可以使用df.query('brand == "Python"')進行查找,也可以使用df[df['brand'] == "Python"]這種方式進行查找。

out:

df數據打印:
? ? ?brand ? A ? B ? C ? D ?till years
0 ?Python ?10 ? 4 ? 8 ? 6 ? ? ? ? ? 4
1 ? ? ?C ? ?2 ? 6 ?12 ?18 ? ? ? ? ? 1
2 ? ?C++ ? ?5 ? 8 ?18 ?14 ? ? ? ? ? 1
3 ? ? ?C# ?20 ?12 ? 8 ? 6 ? ? ? ? ?30
4 ? ?Java ?16 ?10 ? 2 ?12 ? ? ? ? ?30
?
查找數據:
? ? ?brand ? A ?B ?C ?D ?till years
0 ?Python ?10 ?4 ?8 ?6 ? ? ? ? ? 4
?
查找數據:
? ? ?brand ? A ?B ?C ?D ?till years
0 ?Python ?10 ?4 ?8 ?6 ? ? ? ? ? 4
通過數學表達式來篩選:

除了直接通過等于某個值來篩選, query 函數還支持通過數學表達式來進行數據篩選,包括 > 、 < 、 + 、 - 、 * 、 / 等。

print('查找數據:\n', df.query('A > 15'), '\n')

out:

查找數據:
? ?brand ? A ? B ?C ? D ?till years
3 ? ?C# ?20 ?12 ?8 ? 6 ? ? ? ? ?30
4 ?Java ?16 ?10 ?2 ?12 ? ? ? ? ?30

通過變量篩選:

在程序比較長的時候,經常會使用變量來作為篩選條件, query 函數在使用變量作為判斷標準時,通過在變量前面添加 @ 符號來實現,

示例如下:

name = 'Java'
print('查找數據:\n', df.query('brand == @name'), '\n')

out:

查找數據:
? ?brand ? A ? B ?C ? D ?till years
4 ?Java ?16 ?10 ?2 ?12 ? ? ? ? ?30
通過列表數據篩選:

當需要在某列中篩選多個符合要求的值的時候,可以通過列表( list )來實現,示例如下:

name = ['Python', 'Java']
print('查找數據:\n', df.query('brand in @name'), '\n')

out:

查找數據:
? ? ?brand ? A ? B ?C ? D ?till years
0 ?Python ?10 ? 4 ?8 ? 6 ? ? ? ? ? 4
4 ? ?Java ?16 ?10 ?2 ?12 ? ? ? ? ?30

多條件篩選:

  • 兩者都需要滿足的并列條件使用符號 & , 或單詞 and
  • 只需要滿足其中之一的條件使用符號 | , 或單詞 or
name = ['Python', 'Java']
print('查找數據:\n', df.query('brand in @name & A > 15'), '\n')

out:

查找數據:
? ?brand ? A ? B ?C ? D ?till years
4 ?Java ?16 ?10 ?2 ?12 ? ? ? ? ?30

列名稱中有空格的情況,使用``進行處理:

使用引號處理的話,會報錯。

print('查找數據:\n', df.query('`till years` > 10'), '\n')

out:

查找數據:
? ?brand ? A ? B ?C ? D ?till years
3 ? ?C# ?20 ?12 ?8 ? 6 ? ? ? ? ?30
4 ?Java ?16 ?10 ?2 ?12 ? ? ? ? ?30

篩選后選取數據列:

name = ['brand', 'A', 'B', 'till years']
print('查找數據:\n', df.query('`till years` > 10')[name], '\n')

out:

查找數據:
? ?brand ? A ? B ?till years
3 ? ?C# ?20 ?12 ? ? ? ? ?30
4 ?Java ?16 ?10 ? ? ? ? ?30

總結:

當用到多條件篩選時,使用query就會顯得簡潔的多:

print(df[(df['brand'] == 'Python') & (df['A'] == 10) & (df['B'] == 4)])
print(df.query('brand == "Python" & A == 10 & B == 4'))

原文鏈接:https://blog.csdn.net/xiadeliang1111/article/details/126819918

欄目分類
最近更新