Pandasのデータフレームを検索する方法をご紹介する。
[toc]使用するデータ
import pandas as pd # List of Tuples students = [ ('jack', 34, 'Sydeny' , 'Australia') , ('Riti', 30, 'Delhi' , 'India' ) , ('Vikas', 31, 'Mumbai' , 'India' ) , ('Neelu', 32, 'Bangalore' , 'India' ) , ('John', 16, 'New York' , 'US') , ('Mike', 17, 'las vegas' , 'US') ] #Create a DataFrame object df = pd.DataFrame(students, columns = ['Name' , 'Age', 'City' , 'Country']) df

文字列の完全一致
# johnを探す df[df["Name"] == "John"]
文字列の部分一致
# 名前にaが含まれるデータを探す df[df.Name.str.contains("a")]
Not条件
否定は「〜」を先頭につける。
# 名前にeeが含まれない人を探す df[(~df.Name.str.contains("ee"))]
数値の比較
# 年齢が30歳以上の人を探す df[df["Age"] >= 30]
AND条件
# インドで31歳以上の人を探す df[(df["Age"] >= 31) & (df["Country"] == "India")]
OR条件
# インドもしくはアメリカの人を探す df[(df["Country"] == "India") | (df["Country"] == "US")]
PythonユーザのためのJupyter[実践]入門 Kindle版
posted with カエレバ