pandasのDataFrame型における行の抽出方法として、str/queryを使った方法を記載する。


まとめ
# 条件を指定して行を抽出
DataFrame型[条件]
DataFrame型.query('条件'))
# 部分一致の行を抽出
## 文字列を含む
DataFrame型[DataFrame型の列.str.contains('文字列')]
## 特定の先頭文字列
DataFrame型[DataFrame型の列.str.startswith('文字列')]
## 特定の末尾文字列
DataFrame型[DataFrame型の列.str.endswith('文字列')]
条件を指定して行を抽出
書き方
以下のようにDataFrame型の列を使用して条件を指定する。
DataFrame型[条件]
もしくは以下のようにqueryを使って条件を指定する。この場合、シングルクォーテーションで囲う必要がある。
DataFrame型.query('条件'))
サンプルコード
# サンプル
import pandas as pd
list_data = [[1, 'apple cake', 100],[2, 'orange cake', 30],[3, 'lemon pie', 50]]
df_list = pd.DataFrame(list_data, columns=["id","name","price"])
# DataFrame型の列を使用する場合
print(df_list[df_list['name']=='orange cake'])
## 出力
# id name price
# 1 2 orange cake 30
print(df_list[df_list['price'] >= 50])
## 出力
# id name price
# 0 1 apple cake 100
# 2 3 lemon pie 50
# queryを使用する場合
print(df_list.query('name == "orange cake"'))
## 出力
# id name price
# 1 2 orange cake 30
print(df_list.query('price >= 50'))
# 出力
# id name price
# 0 1 apple cake 100
# 2 3 lemon pie 50


部分一致の行を抽出
書き方
文字列の部分一致は以下のようにstrを使用する。以下以外にもメソッドはある。
## 文字列を含む
DataFrame型[DataFrame型の列.str.contains('文字列')]
## 特定の先頭文字列
DataFrame型[DataFrame型の列.str.startswith('文字列')]
## 特定の末尾文字列
DataFrame型[DataFrame型の列.str.endswith('文字列')]
サンプルコード
# サンプル
import pandas as pd
list_data = [[1, 'apple cake', 100],[2, 'orange cake', 30],[3, 'lemon pie', 50]]
df_list = pd.DataFrame(list_data, columns=["id","name","price"])
## 文字列を含む
print(df_list[df_list['name'].str.contains('a')])
## 出力
# id name price
# 0 1 apple cake 100
# 1 2 orange cake 30
## 特定の先頭文字列
print(df_list[df_list['name'].str.startswith('apple')])
## 出力
# id name price
# 0 1 apple cake 100
## 特定の末尾文字列
print(df_list[df_list['name'].str.endswith('cake')])
## 出力
# id name price
# 0 1 apple cake 100
# 1 2 orange cake 30

まとめ
# 条件を指定して行を抽出
DataFrame型[条件]
DataFrame型.query('条件'))
# 部分一致の行を抽出
## 文字列を含む
DataFrame型[DataFrame型の列.str.contains('文字列')]
## 特定の先頭文字列
DataFrame型[DataFrame型の列.str.startswith('文字列')]
## 特定の末尾文字列
DataFrame型[DataFrame型の列.str.endswith('文字列')]
