1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

pandasチートシート

1
Last updated at Posted at 2025-11-02

データ分析業務において、pandasのデータフレームを頻用するので、よくやる動作を以下にまとめる。

pandasのインポート

inport pandas as pd

慣例でpdと命名する。

空のデータフレームの作成とデータの追加

空のデータフレームの作成

df = pd.DataFrame(columns=["名前", "年齢", "職業"])

columns=["名前", "年齢", "職業"]を入れなければ、列名も指定せずに作成することができる。

データフレームにデータを追加する

df.loc[len(df)] = ["田中", 25, "エンジニア"]
df.loc[len(df)] = ["山田", 28, "医者"]
df.loc[len(df)] = ["佐藤", 35, "教師"]
df

出力
スクリーンショット 2025-11-03 3.59.51.png

データフレーム内でループを回す

for index, row in df.iterrows():
    print(index)
    print(row['年齢'], row['名前'], row['職業'])

出力

0
25 田中 エンジニア
1
28 山田 医者
2
35 佐藤 教師

データフレームからデータを抽出する

特定の要素を含む行の抽出

new_df = df[df['名前'] == '田中']
new_df

出力
スクリーンショット 2025-11-03 4.07.35.png

以下のようにすると、部分一致も抽出できる。

new_df = df[df["名前"].str.contains("田", na=False)]
new_df

スクリーンショット 2025-11-03 4.07.35のコピー.png

1
1
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
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?