pandasパターン - 抽出

前置き

以下のテーブルを準備します。

import pandas as pd

# C: col => 列名
# R: row => 行名 
d = {"C1": [1, 2, 3],
     "C2": [2, 4, 6],
     "C3": [3, 6, 9]}
r = ["R1", "R2", "R3"]
df = pd.DataFrame(d, index=r)

行名, 列名がわかっている場合

df.loc["R1", :]  # 行の抽出
df["C1"]         # 列の抽出

行や列の値に応じて抽出

df.query("C1 == 1")              # 行の抽出
df.loc[:, df.loc["R1", :] == 1]  # 列の抽出

行名,列名の文字列から検索して抽出

特定の文字を含む行や列を抽出

df.loc[df.index.str.contains(""), :]      # 行の抽出
df.loc[:, df.columns.str.contains("")]   # 列の抽出

行名,列名が特定の値から始まる/終わる行や列を抽出

df.loc[df.index.str.startswith(""), :]    # 行の抽出
df.loc[df.index.str.endswith(""), :]      # 行の抽出
df.loc[:, df.columns.str.startswith("")]  # 列の抽出
df.loc[:, df.columns.str.endswith("")]    # 列の抽出