0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

概観

NumPy       -> ndarray / 数値計算 / ベクトル化 / ブロードキャスト / 行列演算
Pandas      -> Series / DataFrame / ラベル付きデータ / 集計 / ピボット / 欠損値 / 結合
Matplotlib  -> plot / scatter / bar / hist / subplot / Figure / Axes
Seaborn     -> Matplotlib ベースの高水準可視化ライブラリ

データサイエンティストのためのPythonライブラリ応用(上級編)

第1部:NumPy

1. 位置づけ

キーワード:ndarray、ベクトル化、行列演算、ブロードキャスト、ユニバーサル関数、統計処理。

2. NumPy を使う場面

2.1 向いている場面

  • 大量の数値計算
  • for ループの大半が配列や行列の逐次処理になっている場面
  • 行列積、ブロードキャスト、集計をまとめて行いたい場面

2.2 速い理由

  • C 実装
  • 連続したメモリ配置
  • 同じ dtype をまとめて扱える
  • Python レベルのループを減らせる
  • 線形代数ライブラリの最適化を利用できる

2.3 優先して使いたい場面

  • 同種の数値データをまとめて扱うとき
  • 一括演算に置き換えられるとき
  • ランダムデータや行列計算を多用するとき

3. NumPy 配列の作成

3.1 リストから作る

import numpy as np

np.array([1, 2, 3])                    # リストから ndarray を作成
np.array([1, 2, 3], dtype="float32")   # dtype を指定して作成

3.2 固定値の配列

np.zeros((2, 3))     # 0 で埋めた配列
np.ones((2, 3))      # 1 で埋めた配列
np.full((2, 3), 7)   # 指定値で埋めた配列
np.eye(3)            # 3x3 の単位行列

3.3 連番・等間隔の配列

np.arange(0, 10, 2)  # 左閉右開で等間隔の整数列
np.linspace(0, 1, 5) # 要素数を指定した等間隔列
np.logspace(0, 3, 4) # 対数スケールの等比列

3.4 乱数配列

np.random.seed(42)                 # 乱数シードを固定
np.random.random((2, 3))           # [0, 1) の一様乱数
np.random.randint(0, 10, 5)        # 乱数整数
np.random.permutation(5)           # 並び替えたコピーを返す
x = np.arange(5)
np.random.shuffle(x)               # 元の配列をその場でシャッフル
np.random.choice([1, 2, 3], 2)     # 抽出

4. NumPy 配列の基本

4.1 属性

arr.shape  # 形状
arr.ndim   # 次元数
arr.size   # 要素数
arr.dtype  # データ型

4.2 インデックス

x[0]     # 先頭要素
x[-1]    # 末尾要素
x[0, 0]  # 2 次元配列の推奨書式
x[0][0]  # 2 段階でも取れるが通常は上を使う

4.3 スライス

  • スライスは通常ビューを返す。独立したコピーが必要なら copy() を使う。
x[1:5:2]         # 1 次元スライス
x[:2, :3]        # 2 次元スライス
x[1]             # 2 行目
x[:, 2]          # 3 列目
x[:2, :3].copy() # 独立コピー

4.4 形状変更

x.reshape(2, 3)  # 形状を変更
x.reshape(-1)    # 1 次元へ展開
x.ravel()        # 可能ならビューとして展開
x.flatten()      # コピーとして展開

4.5 結合

np.hstack([a, b])  # 水平方向に結合
np.vstack([a, b])  # 垂直方向に結合
np.c_[a, b]        # 列方向の簡易結合
np.r_[a, b]        # 行方向の簡易結合

4.6 分割

np.split(x, 2)        # 汎用分割
np.hsplit(x, 2)       # 水平方向に分割
np.vsplit(x, 2)       # 垂直方向に分割
np.array_split(x, 3)  # 等分できない場合の分割

5. NumPy の基本演算

5.1 ベクトル化演算

x + 5      # 全要素にスカラーを加える
x * 2      # 全要素を 2 倍する
x1 + x2    # 同じ形状どうしの要素ごとの加算
np.exp(x)  # 指数関数
np.log(x)  # 自然対数

5.2 行列演算

x.T       # 転置
x.dot(y)  # 内積 / 行列積
x @ y     # 行列積の簡潔な書き方

5.3 ブロードキャスト

  • 末尾の次元から比較し、次元が同じか、どちらかが 1 なら拡張される。
np.arange(3) + 5               # 1 次元配列 + スカラー
np.ones((3, 3)) + np.arange(3) # 行方向に拡張して加算
np.ones((3, 1)) + np.arange(3) # 列ベクトルと行ベクトルの加算

5.4 比較演算とマスク

用途:条件抽出、異常値確認、条件付き置換。

mask = x > 3            # ブールマスク
x[mask]                 # 条件に合う要素だけ抽出
x[(x > 3) & (x < 8)]    # 条件の組み合わせ
np.where(x > 3, 1, 0)   # 条件に応じた値の切り替え

5.5 ファンシーインデックス

用途:非連続な位置の一括取得。

x[[0, 2, 4]]         # 1 次元の位置指定取得
x[row, col]          # 行列の座標指定取得
x[[0, 1], [1, 2]]    # (0,1) と (1,2) を取得
np.take(x, [0, 2])   # インデックス配列で取得

6. NumPy の汎用関数と統計

6.1 ソート

np.sort(x)     # ソート後の値
np.argsort(x)  # ソート順のインデックス

6.2 最大値・最小値

np.max(x)     # 最大値
np.min(x)     # 最小値
np.argmax(x)  # 最大値の位置
np.argmin(x)  # 最小値の位置

6.3 合計・積

np.sum(x)          # 合計
np.prod(x)         # 総積
np.sum(x, axis=0)  # 縦方向に集約
np.sum(x, axis=1)  # 横方向に集約

6.4 基本統計量

np.mean(x)    # 平均
np.var(x)     # 分散
np.std(x)     # 標準偏差
np.median(x)  # 中央値

7. NumPy 要点ツリー

NumPy
├─ 使いどころ
│  ├─ 大量の数値計算
│  └─ ベクトル化 / ブロードキャスト / 行列演算
├─ 配列作成
│  ├─ リスト: np.array
│  ├─ 固定値: np.zeros / np.ones / np.full / np.eye
│  ├─ 連番: np.arange / np.linspace / np.logspace
│  └─ 乱数: np.random.seed / np.random.random / np.random.randint / np.random.permutation / np.random.shuffle / np.random.choice
├─ 配列の基本
│  ├─ 属性: arr.shape / arr.ndim / arr.size / arr.dtype
│  ├─ インデックス: x[0] / x[-1] / x[0, 0]
│  ├─ スライス: x[1:5:2] / x[:2, :3] / copy()
│  ├─ 形状変更: reshape / ravel / flatten
│  ├─ 結合: np.hstack / np.vstack / np.c_ / np.r_
│  └─ 分割: np.split / np.hsplit / np.vsplit / np.array_split
├─ 演算
│  ├─ ベクトル化: + - * / // % / np.exp / np.log
│  ├─ 行列演算: T / dot / @
│  ├─ ブロードキャスト: スカラー拡張 / 次元 1 の拡張
│  ├─ 比較とマスク: > < == / x[mask] / np.where
│  └─ ファンシーインデックス: x[[...]] / x[row, col] / np.take
└─ 統計
   ├─ ソート: np.sort / np.argsort
   ├─ 極値: np.max / np.min / np.argmax / np.argmin
   ├─ 集約: np.sum / np.prod / axis
   └─ 基本統計: np.mean / np.var / np.std / np.median

第2部:Pandas

1. 位置づけ

キーワード:SeriesDataFrame、ラベル付きデータ、欠損値処理、結合、グループ化、ピボットテーブル。

2. Pandas の特徴

NumPy  -> 配列中心の数値計算
Pandas -> 表形式データの操作、ラベルによる参照、集計と整形

3. Pandas オブジェクトの作成

3.1 1 次元オブジェクト:Series

import numpy as np
import pandas as pd

pd.Series([1, 2, 3])             # リストから Series を作成
pd.Series({"a": 1, "b": 2})    # 辞書から Series を作成
pd.Series(np.array([1, 2, 3]))   # ndarray から Series を作成

3.2 2 次元オブジェクト:DataFrame

pd.DataFrame({"name": ["A", "B"], "score": [90, 85]})             # 辞書から作成
pd.DataFrame([{"a": 1, "b": 2}, {"a": 3, "b": 4}])               # 辞書のリストから作成
pd.DataFrame(np.array([[1, 2], [3, 4]]), columns=["a", "b"])         # 2 次元 ndarray から作成

4. Pandas の属性

df.values   # 実データ
df.index    # 行ラベル
df.columns  # 列ラベル
df.shape    # 形状
df.size     # 要素数
df.dtypes   # 各列の型

5. DataFrame の参照・スライス・代入

5.1 列の取得

df["name"]               # 1 列を取得
df[["name", "score"]]   # 複数列を取得
df.name                   # 属性形式で取得できる場合もある

5.2 行の取得

df.loc["a"]                 # ラベルで行を取得
df.iloc[0]                  # 位置で行を取得
df.loc["a":"c", ["name"]] # 行と列を同時に指定

5.3 行スライス

df["a":"c"]  # ラベルによる行スライス
df.iloc[0:3]   # 位置による行スライス

5.4 列スライス

df.loc[:, "col1":"col3"]  # ラベルによる列スライス
df.iloc[:, 0:3]             # 位置による列スライス

5.5 比較演算とブールインデックス

用途:条件抽出、部分集合の作成、異常値の確認。

df["score"] > 80                  # 条件式
df[df["score"] > 80]              # 条件に合う行を抽出
df.query("score > 80")            # query による抽出
df.loc[df["score"] > 80, "name"]  # 条件付きで特定列を取得

5.6 代入

df["new_col"] = value                      # 列を追加 / 上書き
df.loc[df["score"] > 80, "level"] = "A"  # 条件付き代入
df.iloc[0, 0] = "X"                        # 位置指定代入

5.7 index と columns の変更

df.index = ["a", "b"]                          # 行ラベルを直接変更
df.columns = ["name", "score"]                # 列ラベルを直接変更
df.rename(columns={"score": "final_score"})   # 列名変更
df.reset_index(drop=True)                       # インデックスを振り直す
df.set_index("name")                           # 列をインデックスにする

6. データ確認

df.head()  # 先頭 5 行
df.tail()  # 末尾 5 行
df.info()  # 列名、件数、型を確認

7. Pandas の数値演算と統計

7.1 ベクトル化演算

df["sum"] = df["a"] + df["b"]     # 列どうしの演算
df["ratio"] = df["a"] / df["b"]   # 要素ごとの割り算

7.2 NumPy 関数との併用

np.log(df["x"])  # Series に対して対数を計算
np.exp(df["x"])  # Series に対して指数を計算

7.3 行列的な計算

df[["a", "b"]] * 2                       # 複数列を一括変換
df[["a", "b"]].dot(np.array([0.3, 0.7]))  # 重み付き和

7.4 ブロードキャストと自動整列

df + 1                                   # スカラー加算
df.sub(df.mean(numeric_only=True))       # 列名をそろえて減算
s = pd.Series({"a": 1, "b": 2})
df[["a", "b"]].add(s, axis="columns")   # 列ラベルをそろえて加算

8. カテゴリ集計と並べ替え

8.1 カテゴリ集計

df["col"].unique()         # 一意な値
df["col"].nunique()        # 一意な値の個数
df["col"].value_counts()   # 出現回数

8.2 並べ替え

df.sort_values(by="col")                                      # 1 列で並べ替え
df.sort_values(by=["col1", "col2"], ascending=[False, True])  # 複数列で並べ替え

9. 基本統計量

df.count()                      # 非欠損数
df.sum()                        # 合計
df.max()                        # 最大値
df.min()                        # 最小値
df.mean(numeric_only=True)      # 平均
df.var(numeric_only=True)       # 分散
df.std(numeric_only=True)       # 標準偏差
df.median(numeric_only=True)    # 中央値
df.mode()                       # 最頻値
df.quantile(0.75)               # 分位点
df.corr(numeric_only=True)      # 相関係数
df.cov(numeric_only=True)       # 共分散
df.describe()                   # 要約統計量

10. apply によるカスタム処理

用途:列単位の変換、行単位の判定、文字列処理。

df["col"].apply(func)   # 1 列に関数を適用
df.apply(func, axis=1)  # 行単位で関数を適用
df.applymap(func)       # DataFrame 全体を要素単位で変換

11. 欠損値処理

11.1 欠損値の削除

df.dropna()                   # 欠損を含む行を削除
df.dropna(axis=1)             # 欠損を含む列を削除
df.dropna(subset=["score"])   # 特定列を基準に削除

11.2 欠損値の補完

df.fillna(0)                              # 定数で補完
df["score"].fillna(df["score"].mean())   # 平均値で補完
df.ffill()                               # 前方補完
df.bfill()                               # 後方補完

12. データ結合

12.1 concat

pd.concat([df1, df2], axis=0, ignore_index=True)  # 縦方向に結合
pd.concat([df1, df2], axis=1)                     # 横方向に結合

12.2 merge

pd.merge(df1, df2, on="key", how="inner")  # 内部結合
pd.merge(df1, df2, on="key", how="left")   # 左結合
pd.merge(df1, df2, on="key", how="outer")  # 外部結合

12.3 整列

s1 + s2                      # インデックスで自動整列
df1.add(df2, fill_value=0)   # 整列してから演算
df1.align(df2, join="outer")  # 明示的に整列

13. グループ化とピボットテーブル

13.1 groupby

用途:集約、比較、グループごとのカスタム処理。

df.groupby("group")["value"].mean()                    # 単一集約
df.groupby("group").agg({"value": ["mean", "sum"]})   # 複数集約
df.groupby("group").apply(func)                        # 任意処理

13.2 pivot_table

用途:クロス集計、集計表の作成。

pd.pivot_table(
    df,
    values="value",
    index="row_key",
    columns="col_key",
    aggfunc="mean",
    margins=True  # 合計行・合計列を追加
)

14. Pandas の補足機能

14.1 文字列のベクトル化処理

df["name"].str.lower()             # 小文字化
df["name"].str.contains("abc")    # 部分一致
df["name"].str.extract(r"(\d+)")   # 正規表現で抽出

14.2 時系列処理

pd.to_datetime(df["date"])                  # 日付型へ変換
df.set_index("date").resample("M").sum()   # 月単位で再集計
df["value"].rolling(7).mean()              # 7 期間の移動平均

14.3 MultiIndex

df.set_index(["store", "date"])  # 多重インデックスを設定
df.reset_index()                   # 通常の列に戻す
df.swaplevel()                     # 階層の順序を入れ替える
df.sort_index()                    # インデックスで並べ替える

14.4 eval と query

df.eval("c = a + b")            # 式を文字列で評価
df.query("a > 10 and b < 5")   # 条件式で抽出
  • データが大きいほど、式をまとめて書ける利点が出やすい。

15. Pandas 要点ツリー

Pandas
├─ オブジェクト
│  ├─ Series: pd.Series
│  └─ DataFrame: pd.DataFrame
├─ 属性
│  ├─ df.values / df.index / df.columns
│  └─ df.shape / df.size / df.dtypes
├─ 参照とスライス
│  ├─ 列取得: df["col"] / df[[...]]
│  ├─ 行取得: df.loc[...] / df.iloc[...]
│  ├─ 行スライス: df["a":"c"] / df.iloc[0:3]
│  ├─ 列スライス: df.loc[:, ...] / df.iloc[:, ...]
│  ├─ ブールインデックス: df[cond] / query()
│  └─ 代入: df[col] = ... / df.loc[...] = ... / df.iloc[...] = ...
├─ 確認と統計
│  ├─ 確認: head() / tail() / info()
│  ├─ カテゴリ: unique() / nunique() / value_counts()
│  ├─ 並べ替え: sort_values()
│  ├─ 基本統計: count() / sum() / max() / min() / mean() / var() / std() / median() / mode() / quantile() / describe()
│  └─ 関係性: corr() / cov()
├─ データ処理
│  ├─ 欠損値: dropna() / fillna() / ffill() / bfill()
│  ├─ 結合: concat() / merge() / align()
│  ├─ グループ化: groupby() / agg() / apply()
│  └─ ピボット: pivot_table()
├─ 応用機能
│  ├─ 文字列: str.lower() / str.contains() / str.extract()
│  ├─ 時系列: to_datetime() / set_index() / resample() / rolling()
│  ├─ MultiIndex: set_index() / reset_index() / swaplevel() / sort_index()
│  └─ 式評価: eval() / query()
└─ 演算
   ├─ ベクトル化: 列どうしの直接演算
   ├─ 行列的な計算: dot()
   ├─ 整列付き演算: add() / sub() / align()
   └─ カスタム処理: apply() / applymap()

第3部:Matplotlib

1. 位置づけ

キーワード:plotscatterbarhistsubplot、スタイル、注釈、FigureAxes

2. 環境設定

2.1 Jupyter / IPython

%matplotlib inline  # Notebook 上に画像を直接表示

2.2 PyCharm / スクリプト

import matplotlib.pyplot as plt

plt.show()  # ウィンドウに描画して表示

2.3 plt.show() を使う場面

  • Notebook / IPython では %matplotlib inline を使うことが多い
  • スクリプトや IDE では plt.show() が必要になることが多い

3. スタイル設定

plt.style.use("ggplot")  # 全体のスタイルを設定

with plt.style.context("seaborn-v0_8"):
    ...                   # 一時的にスタイルを切り替える

4. 画像保存

plt.savefig("figure.png", dpi=300, bbox_inches="tight")  # 余白を詰めて高解像度で保存

5. 代表的なグラフ

5.1 折れ線グラフ plot

用途:推移、時系列、連続量の変化。

plt.plot(x, y)  # 折れ線グラフ

5.2 散布図 scatter

用途:相関、外れ値、分布の確認。

plt.scatter(x, y)  # 散布図

5.3 棒グラフ bar

用途:カテゴリ比較、順位比較、集計結果の表示。

plt.bar(x, height)  # 棒グラフ

5.4 ヒストグラム hist

用途:分布、度数、偏りの確認。

plt.hist(x, bins=20)  # ヒストグラム

5.5 誤差付きグラフ errorbar

用途:誤差幅、信頼区間、不確実性の表示。

plt.errorbar(x, y, yerr=error)  # 誤差付きグラフ

6. サブプロット

用途:1 枚の図に複数グラフを並べて比較する。

plt.subplot(2, 2, 1)       # pyplot スタイル
fig, axes = plt.subplots(2, 2)  # オブジェクト指向スタイル

7. グラフの見た目の調整

7.1 線の色・種類・太さ

plt.plot(x, y, color="red", linestyle="--", linewidth=2)  # 色 / 線種 / 線幅

7.2 マーカーの形・大きさ・色

plt.plot(x, y, marker="o", markersize=5, markerfacecolor="blue")  # マーカー設定

7.3 凡例

plt.plot(x, y, label="sales")
plt.legend()  # 凡例を表示

7.4 テキストと注釈

plt.text(x0, y0, "peak")               # 文字を配置
plt.annotate("outlier", xy=(x0, y0))  # 注釈を追加

7.5 タイトルと軸ラベル

plt.title("title")  # タイトルを設定
plt.xlabel("x")     # x 軸ラベルを設定
plt.ylabel("y")     # y 軸ラベルを設定

8. オブジェクト指向の描画

fig, ax = plt.subplots()
ax.plot(x, y, label="sales")  # Axes に描画
ax.set_title("title")   # タイトル
ax.set_xlabel("x")      # x 軸ラベル
ax.set_ylabel("y")      # y 軸ラベル
ax.legend()             # 凡例

9. 3 次元描画

fig = plt.figure()
ax = fig.add_subplot(111, projection="3d")  # 3 次元の Axes を作成
ax.scatter(x, y, z)                          # 3 次元散布図

10. Seaborn

import seaborn as sns

sns.lineplot(data=df, x="x", y="y")        # 高水準の折れ線グラフ
sns.scatterplot(data=df, x="x", y="y")     # 高水準の散布図
sns.histplot(data=df, x="x")               # ヒストグラム
sns.barplot(data=df, x="cat", y="value")   # 棒グラフ
  • Matplotlib を土台にしつつ、見た目と統計グラフの扱いやすさを高めたライブラリ。

11. Pandas の plot メソッド

df.plot()                              # 既定では折れ線グラフ
df.plot(kind="line")                  # 折れ線グラフ
df.plot(kind="scatter", x="a", y="b")  # 散布図
df.plot(kind="bar")                   # 棒グラフ
df.plot(subplots=True)                 # 列ごとに分けて描画

12. Matplotlib 要点ツリー

Matplotlib
├─ 環境設定
│  ├─ Notebook: %matplotlib inline
│  ├─ 表示: plt.show()
│  └─ 保存: plt.savefig()
├─ スタイル
│  ├─ 全体: plt.style.use
│  └─ 一時切替: plt.style.context
├─ グラフ
│  ├─ 折れ線: plt.plot
│  ├─ 散布図: plt.scatter
│  ├─ 棒グラフ: plt.bar
│  ├─ ヒストグラム: plt.hist
│  └─ 誤差表示: plt.errorbar
├─ サブプロット
│  ├─ pyplot: plt.subplot
│  └─ OOP: plt.subplots()
├─ 見た目の調整
│  ├─ タイトルと軸: plt.title / plt.xlabel / plt.ylabel
│  ├─ 線: color / linestyle / linewidth
│  ├─ マーカー: marker / markersize / markerfacecolor
│  ├─ 凡例: label / plt.legend / ax.legend
│  └─ 注釈: plt.text / plt.annotate
├─ オブジェクト指向
│  ├─ plt.subplots()
│  └─ ax.plot / ax.set_title / ax.set_xlabel / ax.set_ylabel / ax.legend
├─ 3 次元
│  └─ fig.add_subplot(..., projection="3d") / ax.scatter
└─ 関連ツール
   ├─ Seaborn: sns.lineplot / sns.scatterplot / sns.histplot / sns.barplot
   └─ Pandas の plot メソッド: df.plot() / df.plot(kind="line") / df.plot(kind="scatter") / df.plot(kind="bar") / df.plot(subplots=True)

第4部:3ライブラリの関係

1. 役割分担

基礎計算:NumPy
表データ処理:Pandas
可視化:Matplotlib
手早い可視化と見た目の調整:Seaborn / Pandas の plot メソッド

2. データ分析フローでの位置

データ準備
├─ NumPy:配列、行列、乱数、数値計算
└─ Pandas:読み込み、確認、整形、欠損値処理、結合

データ分析
├─ NumPy:ベクトル化、ブロードキャスト、統計関数
└─ Pandas:グループ化、ピボット、記述統計、apply、query

データ可視化
├─ Matplotlib:基本グラフ、サブプロット、スタイル、注釈
├─ Pandas の plot メソッド:手早い可視化
└─ Seaborn:統計グラフと見た目の調整

3. コアオブジェクトの比較

ライブラリ コアオブジェクト 主な用途
NumPy ndarray 多次元配列、数値計算、行列演算
Pandas Series / DataFrame 表データ、ラベル参照、集計と整形
Matplotlib Figure / Axes 描画、グラフ管理、可視化出力

4. 連携の基本例

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt

x = np.linspace(0, 10, 100)            # NumPy で数値列を作成
y = np.sin(x)                          # NumPy で計算
df = pd.DataFrame({"x": x, "y": y})   # Pandas で表にまとめる
plt.plot(df["x"], df["y"])            # Matplotlib で描画
plt.show()                           # 表示

第5部:項目一覧

NumPy

  • C 実装 / 連続メモリ / 同一 dtype / ベクトル化
  • リストから作る: np.array
  • 固定値の配列: np.zeros / np.ones / np.full / np.eye
  • 連番・等間隔の配列: np.arange / np.linspace / np.logspace
  • 乱数配列: np.random.seed / np.random.random / np.random.randint / np.random.permutation / np.random.shuffle / np.random.choice
  • 属性: arr.shape / arr.ndim / arr.size / arr.dtype
  • インデックス: x[0] / x[-1] / x[0, 0]
  • スライス: x[1:5:2] / x[:2, :3] / x[1] / x[:, 2]
  • コピー: copy()
  • 形状変更: reshape / ravel / flatten
  • 結合: np.hstack / np.vstack / np.c_ / np.r_
  • 分割: np.split / np.hsplit / np.vsplit / np.array_split
  • ベクトル化演算: + / - / * / / / // / % / np.exp / np.log
  • 行列演算: T / dot / @
  • ブロードキャスト
  • 比較演算とマスク: > / < / == / x[mask] / np.where
  • ファンシーインデックス: x[[...]] / x[row, col] / np.take
  • ソート: np.sort / np.argsort
  • 最大値・最小値: np.max / np.min / np.argmax / np.argmin
  • 合計・積: np.sum / np.prod / axis
  • 基本統計量: np.mean / np.var / np.std / np.median

Pandas

  • 表形式データ / ラベル参照 / 集計 / 整形
  • Series の作成: pd.Series
  • DataFrame の作成: pd.DataFrame
  • 属性: df.values / df.index / df.columns / df.shape / df.size / df.dtypes
  • 列の取得: df["name"] / df[["name", "score"]] / df.name
  • 行の取得: df.loc["a"] / df.iloc[0] / df.loc["a":"c", ["name"]]
  • 行スライス: df["a":"c"] / df.iloc[0:3]
  • 列スライス: df.loc[:, "col1":"col3"] / df.iloc[:, 0:3]
  • 比較演算とブールインデックス: df["score"] > 80 / df[cond] / query()
  • 代入: df[col] = ... / df.loc[...] = ... / df.iloc[...] = ...
  • indexcolumns の変更: df.index = ... / df.columns = ... / rename() / reset_index() / set_index()
  • データ確認: head() / tail() / info()
  • カテゴリ集計: unique() / nunique() / value_counts()
  • 並べ替え: sort_values()
  • 基本統計量: count() / sum() / max() / min() / mean() / var() / std() / median() / mode() / quantile() / describe()
  • 関係性: corr() / cov()
  • ベクトル化演算: + / - / * / /
  • NumPy 関数との併用: np.log / np.exp
  • 行列的な計算: df[["a", "b"]] * 2 / dot()
  • ブロードキャストと自動整列: df + 1 / add() / sub() / align()
  • apply によるカスタム処理: apply() / applymap()
  • 欠損値の削除: dropna()
  • 欠損値の補完: fillna() / ffill() / bfill()
  • データ結合: concat() / merge() / align()
  • グループ化: groupby() / agg() / apply()
  • ピボットテーブル: pivot_table()
  • 文字列のベクトル化処理: str.lower() / str.contains() / str.extract()
  • 時系列処理: to_datetime() / set_index() / resample() / rolling()
  • MultiIndex: set_index() / reset_index() / swaplevel() / sort_index()
  • eval()query()

Matplotlib

  • Jupyter / IPython: %matplotlib inline
  • PyCharm / スクリプト: plt.show()
  • plt.show() を使う場面
  • スタイル設定: plt.style.use / plt.style.context
  • 画像保存: plt.savefig()
  • 折れ線グラフ: plt.plot
  • 散布図: plt.scatter
  • 棒グラフ: plt.bar
  • ヒストグラム: plt.hist
  • 誤差付きグラフ: plt.errorbar
  • サブプロット: plt.subplot / plt.subplots
  • タイトルと軸ラベル: plt.title / plt.xlabel / plt.ylabel
  • 線とマーカー: color / linestyle / linewidth / marker / markersize / markerfacecolor
  • 凡例: label / plt.legend / ax.legend
  • テキストと注釈: plt.text / plt.annotate
  • オブジェクト指向の描画: plt.subplots() / ax.plot / ax.set_title / ax.set_xlabel / ax.set_ylabel / ax.legend
  • 3 次元描画: fig.add_subplot(..., projection="3d") / ax.scatter
  • Seaborn: sns.lineplot / sns.scatterplot / sns.histplot / sns.barplot
  • Pandas の plot メソッド: df.plot() / df.plot(kind="line") / df.plot(kind="scatter") / df.plot(kind="bar") / df.plot(subplots=True)

第6部:要点ツリー

Python データ分析 3 ライブラリ
├─ NumPy
│  ├─ 作成: np.array / np.zeros / np.ones / np.full / np.eye / np.arange / np.linspace / np.logspace
│  ├─ 乱数: np.random.seed / np.random.random / np.random.randint / np.random.permutation / np.random.shuffle / np.random.choice
│  ├─ 属性: arr.shape / arr.ndim / arr.size / arr.dtype
│  ├─ インデックス: x[0] / x[-1] / x[0, 0]
│  ├─ スライスとコピー: x[1:5:2] / x[:2, :3] / copy()
│  ├─ 形状変更: reshape / ravel / flatten
│  ├─ 結合と分割: np.hstack / np.vstack / np.c_ / np.r_ / np.split / np.hsplit / np.vsplit / np.array_split
│  ├─ ベクトル化演算: + - * / / // % / np.exp / np.log
│  ├─ 行列演算: T / dot / @
│  ├─ ブロードキャスト: スカラー拡張 / 次元 1 の拡張
│  ├─ 比較とマスク: > / < / == / x[mask] / np.where
│  ├─ ファンシーインデックス: x[[...]] / x[row, col] / np.take
│  ├─ ソートと極値: np.sort / np.argsort / np.max / np.min / np.argmax / np.argmin
│  └─ 集約と統計: np.sum / np.prod / np.mean / np.var / np.std / np.median
├─ Pandas
│  ├─ 作成: pd.Series / pd.DataFrame
│  ├─ 属性: df.values / df.index / df.columns / df.shape / df.size / df.dtypes
│  ├─ 参照とスライス: df["col"] / df[[...]] / df.loc[...] / df.iloc[...] / df["a":"c"] / df.loc[:, ...]
│  ├─ 条件抽出と代入: df[cond] / query() / df[col] = ... / df.loc[...] = ... / df.iloc[...] = ...
│  ├─ index / columns の変更: df.index = ... / df.columns = ... / rename() / reset_index() / set_index()
│  ├─ 確認と集計: head() / tail() / info() / unique() / nunique() / value_counts() / sort_values()
│  ├─ 基本統計: count() / sum() / max() / min() / mean() / var() / std() / median() / mode() / quantile() / describe()
│  ├─ 関係性: corr() / cov()
│  ├─ 数値演算と整列: + - * / / np.log / np.exp / dot() / add() / sub() / align()
│  ├─ 欠損値と結合: dropna() / fillna() / ffill() / bfill() / concat() / merge()
│  ├─ 集約と変換: groupby() / agg() / apply() / pivot_table() / applymap()
│  └─ 応用: str.lower() / str.contains() / str.extract() / to_datetime() / resample() / rolling() / swaplevel() / sort_index() / eval() / query()
└─ Matplotlib
   ├─ 環境と保存: %matplotlib inline / plt.show() / plt.savefig()
   ├─ スタイル: plt.style.use / plt.style.context
   ├─ 基本グラフ: plt.plot / plt.scatter / plt.bar / plt.hist / plt.errorbar
   ├─ サブプロット: plt.subplot / plt.subplots
   ├─ 見た目の調整: plt.title / plt.xlabel / plt.ylabel / color / linestyle / linewidth / marker / markersize / markerfacecolor / label / plt.legend / plt.text / plt.annotate
   ├─ オブジェクト指向: plt.subplots() / ax.plot / ax.set_title / ax.set_xlabel / ax.set_ylabel / ax.legend
   ├─ 3 次元描画: fig.add_subplot(..., projection="3d") / ax.scatter
   └─ 関連: sns.lineplot / sns.scatterplot / sns.histplot / sns.barplot / df.plot() / df.plot(kind="line") / df.plot(kind="scatter") / df.plot(kind="bar") / df.plot(subplots=True)
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?