LoginSignup
3
5

More than 5 years have passed since last update.

Pandas(Python) For Beginners.

Posted at

Pandas(Python) For Beginners.

 実行環境

  • Python3.6.5
  • iMac (Retina 5K, 27-inch, 2017)
  • プロセッサー 4.2 GHz Intel Core i7
  • macOS High Sierra Ver.10.13.3

Code作成の経緯

これまで、いくつもの会社のデータは、
"Excel"という名の煉獄で管理されていた。
そこに住むのは、悪魔よりももっと以前に存在していたと言う
マザーの手によるものだった...

...今回は、そんな煉獄から脱出する為に、
複数のファイルを一つに統合する術を学ぶ。
検索かけても柔軟性がなく、
やっつけみたいな記事しか引っかからないから、
どんな環境においても柔軟に実行可能なように書いてみた。

実際のCode.

#!/usr/bin/python
# -*- coding: UTF-8 -*-
import os, sys
dirpath = os.path.dirname(os.path.abspath(__file__))
sys.path.append(dirpath)
os.chdir(dirpath)

import pandas as pd
import numpy as np
import math

INPUT_FILE  = {}
OUTPUT_FILE = 'OutPut_File.xlsx'

ROOT = os.path.realpath('.') + '/'

DATAS = {}

def make_tree(dir_path=ROOT):
    file_dict = {}
    dir_path = dir_path.rstrip('/')
    def recur(path, list):
        for l in os.listdir(path):
            f = os.path.join(path, l)
            if l[0] == '.':
              continue
            elif os.path.isdir(f):
                list[l] = {}
                recur(f, list[l])
            elif l.split('.')[-1] in ['xlsx','xls']:
                list[l] = f[len(dir_path)+1:]
    recur(dir_path, file_dict)
    return file_dict

if __name__ == '__main__':
    tree = make_tree(ROOT)
    INPUT_FILE = list(tree)
    OUTBOOK = pd.ExcelWriter(OUTPUT_FILE)
    for n in range(len(tree)):
        with pd.ExcelFile(INPUT_FILE[n]) as WORKBOOK:
            SHEET_NAMES = WORKBOOK.sheet_names
            for t in range(len(SHEET_NAMES)):
                DATAS[SHEET_NAMES[t]] = pd.read_excel(WORKBOOK,  SHEET_NAMES[t], header=None)
                print(f'Fil_Name: {INPUT_FILE[n]}, Sheet_Name: {SHEET_NAMES[t]}')
                df = pd.DataFrame(DATAS[SHEET_NAMES[t]])
                df.to_excel(OUTBOOK,  sheet_name=SHEET_NAMES[t],header=False, index=False, index_label=None)

    OUTBOOK.save()

以上、これで一歩先に行くことができた...次は、統合されたファイルよりテーブル化する。

課題

  • 処理に掛かった経過時間。
  • メモリを監視。
  • サブディレクトリのファイルも処理可能にする

:::注意:::

現在(2018/05/24 初投稿日)は、同一ディレクトリー内に'xlsx','xls'を読み込んでいるがサブディレクトリー処置は施していない為、サブディレクトリーがある下層ではエラーになる。
今後対応予定 (いつかは未定)

3
5
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
3
5