0
4

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.

(openpyxlではなく)PandasでExcelのデータを操作する時のメモ

Posted at

はじめに

以下の本はExcelの処理をPythonで色々するのにお役立ちコードがいろいろ書いているのでオススメです。

とはいえ、この本では「openpyxlというモジュールを使いましょう」ということでサンプルコードが書かれています。それはそれで便利なのですが、会社のeラーニングでPythonを学習すると、やはり

  • numpy
  • Pandas
  • matplotlib

といった三点セットが紹介されることが多いので、今回はこのサンプルコードをPandas対応することとしました。その備忘録です。

気を付けたことメモ

ファイルに書き出すときは「index=False」に気を付ける

しばしば忘れてしまうのですが、PandasのDataframeをそのままExcelに書き出すと、出力先ではindexが付記されるので、データが一列ずれることになります。「読みだしたExcelに書き出す(上書き保存する)」などという処理をしている場合 ファイルが壊れる などとなってしまうことになるので要注意です。

Shift_JIS か UTF-8 か

元Excelを別人が作っている場合もあるので、その際は文字コードが何かを調べるところからが重要です。すべてAsciiなら問題ないんですが…

ChatGPTでサンプルを書いたらまず実行テスト

ChatGPTにサンプルコードを書かせるのは便利で、私もよく使っています。

https://note.com/hideh_hash_845/n/n68863ceb89a4?

が、warningを吐くようなコードが多い気がします。とりあえず書くだけならignoreしておけばいいのですが、そうでないなら原因くらいは調べておいた方がいいかもしれません。

sample

これ自体は特に変哲もないソースコードです。

sales_list_getter_test.py
#!/usr/bin/env python
# coding: shift_jis

# 必要なモジュールのインポート
import pandas as pd

# 不要な警告を非表示にする
import warnings
warnings.filterwarnings('ignore')

# 入力Excelのファイル名、シート名
in_file    = 'sales_list_2023.xlsx'
in_sheet_1 = '売上一覧'

# 出力Excelファイル名
out_file    = '00_OutData.xlsx'
out_sheet_a = 'new_sheet'

#----------
# Excelの読込
in_df1 = pd.read_excel(in_file, sheet_name=in_sheet_1)

# 読込み位置とindexを指定
df1 = in_df1[0:]

# 必要な列のみ抽出
df_columns = ['商品', '売上金額']
df1_work = df1.loc[:, df_columns]

# 商品のsumを作る
out_df1 = df1_work.groupby('商品', as_index=False).sum()

# 総計を追加
sum_all = df1_work['売上金額'].sum()
sum_df = pd.DataFrame([['', sum_all]], index=['SUM'], columns=df_columns)
out_df1 = pd.concat(
    [out_df1, sum_df],
    axis=0,
    ignore_index=True
)

# indexを振り直してファイル書き出し
out_df1 = out_df1.reset_index(drop=True)
with pd.ExcelWriter(out_file) as writer:
    out_df1.to_excel(writer, sheet_name=out_sheet_a, index=False)
    in_df1.to_excel(writer, sheet_name='orig_01')

(おわり)

0
4
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
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?