2
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?

More than 1 year has passed since last update.

【Python入門 第9章】pandas×Excelで業務効率化📊表データの読み書きを完全マスター🐍✨

2
Last updated at Posted at 2025-08-06

【Python入門 第9章】pandas×Excelで業務効率化📊表データの読み書きを完全マスター🐍✨

こんにちは、 PythonTimesの蛇ノ目いろは です🌿
今回は「pandas」を使った Excelファイルの操作 についてやさしく解説するよ!


📚 pandasとは?

表形式のデータ(表計算やCSV/Excelなど)を扱うための最強ライブラリ!

pandasを使えば、Excelみたいな表データもPythonでラクラク操作できちゃう✨

まずはインストール👇

pip install pandas openpyxl

※ Excelファイルの読み書きには openpyxl も必要だよ!


📥 Excelファイルを読み込む(read_excel)

import pandas as pd

df = pd.read_excel("sample.xlsx", sheet_name="Sheet1")
print(df)
  • df は DataFrame(表データの入れ物)
  • sheet_name を省略すると1枚目のシートが読み込まれるよ

📤 Excelファイルに書き出す(to_excel)

df.to_excel("output.xlsx", sheet_name="結果", index=False)
  • index=False にすると、行番号(インデックス列)が書き出されなくなる!

🔍 データの基本操作

print(df.head())       # 先頭5行だけ表示
print(df.columns)      # 列名一覧
print(df["氏名"])       # 指定列のデータ取得
print(df[df["点数"] >= 80])  # 条件フィルタ

✏️ データの追加・変更

行の追加

new_row = {"氏名": "いろは", "点数": 95}
df = pd.concat([df, pd.DataFrame([new_row])], ignore_index=True)

列の追加・変更

df["評価"] = df["点数"].apply(lambda x: "合格" if x >= 70 else "不合格")

💡 Excel特有の便利オプション

  • 特定の列だけ読み込みたいとき:
df = pd.read_excel("sample.xlsx", usecols=["氏名", "点数"])
  • 2枚目以降のシートも読み込める:
df2 = pd.read_excel("sample.xlsx", sheet_name="集計")

✍️ PEP8的なポイント

  • import pandas as pd が一般的なエイリアス(略記)
  • データ変数名は df , data_frame , result_df のように 明示的に ** - 複雑な処理は lambda より ** 関数定義(def) を使うと読みやすくなるよ

📌 まとめ

  • pandasは 表形式データの扱いに特化したライブラリ !
  • read_excel , to_excel でExcelをらくらく読み書き📂
  • apply , フィルタ, 列操作などで 業務自動化も夢じゃない! ** - 命名やインデントも ** PEP8スタイル でスッキリ書こう✨

次回は、
「第10章:Webスクレイピング入門」 をお届け予定🌐
ネットの情報を自動で集める魔法を体験してみよう!

フォローしてくれたらうれしいな🐍📊

2
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
2
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?