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?

More than 3 years have passed since last update.

Python pandasでExcel集計 その2 可変引数

Last updated at Posted at 2020-12-15

##モチベーション
Python pandasでExcel集計 その1の続きです。
dictを繋げる関数を2回呼び出している箇所がダサい。1関数にしたい。
解決策の1つとして、可変引数化する。

##環境
windows10
python3.9
VS Code
Pandas
openpyxl

##準備
python、pandasのinstall(pip使ってね)は済んでる前提

早速答え

pandas_lib.pyで2関数定義

dict型の引数を複数持てる関数concatenateDictsを追加。

pandas_lib.py
import pandas as pd # pandasは、Pythonにおいて、データ解析を支援する機能を提供するライブラリ
import numpy as np

# keyでGroupingしてカウント
def countByKeyFromFileAndSheet(filename, sheetname, key):
  df = pd.read_excel(filename, sheet_name=sheetname, engine="openpyxl")
  dict = df[key].value_counts().to_dict()
  return dict

def concatenateDicts(*dicts):
  newdict = {} # empty dict

  for dict in dicts:
    print(dict)
    for k in dict:
        if k in newdict: # key detected in newdict
          newdict[k] += dict[k]
        else: # not detected
          newdict[k] = dict[k]  
  return newdict

pandas_main.py

concatenateDictを2回呼び出していたところをconcatenateDictsの一回呼び出しにできた。

pandas_main.py
import pandas_lib as pl

dict1 = pl.countByKeyFromFileAndSheet("./example.xlsx", "Sheet1", "部署")
dict2 = pl.countByKeyFromFileAndSheet("./example.xlsx", "Sheet2", "部署")
dict3 = pl.countByKeyFromFileAndSheet("./example.xlsx", "Sheet3", "部署")

dict = pl.concatenateDicts(dict1, dict2, dict3)

print(dict)

実行結果

当然ですが、結果は変わりません。

{'営業部': 4, '開発部': 3, '総務部': 3}
{'営業部': 5, '開発部': 3, '経理部': 2}
{'開発部': 9, '経理部': 1}
{'営業部': 9, '開発部': 15, '総務部': 3, '経理部': 3}
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?