2
2

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 5 years have passed since last update.

DataFrame Mapper というPandasのコードを保守しやすくするライブラリを公開しました

Last updated at Posted at 2018-05-28

DataFrame Mapper というライブラリを PyPI で公開したので、その理由と使い方を説明したいと思います。

作った理由

データ処理を Pandas を使って行うことは一般的だと思いますが、他の人が書いたコードがとても難しく感じ、保守しにくいなぁと思うことがありました。

自分の過去のコードもよくわからないことになっていたので、Pandas が原因の一端の少なくない部分を担っていると思ったので、原因を洗い出してみました。

  • データ処理をスクラッチで書いていくことで意図を表現できない
  • 設計・APIが古い気がする

これを解決するための一つの例としてオブジェクト指向っぽく記述できると、処理に名前が付き、外側には泥臭いところを見せないようにできるのかなぁって思いライブラリを作ってみることにしました。

データ構造をマッピングできるクラスとして実装していて、継承することで

  • 型定義をすることで、どのようなデータを扱っているかを表現している
  • メソッドで処理内容を表現することができる

の2つのことが可能となり、読みやすくて保守しやすくなるのかなぁと思いました。

使い方

使い方は以下のような感じになるように実装しました。

from dfmapper import DataFrameMapper, IntColumn, StrColumn

class UserDfm(DataFrameMapper):

    id = IntColumn(min=1, nullable=False)
    username = StrColumn(max_length=30, nullable=False)
    profile = StrColumn()

    def find_by_id(self, id):
        return self.df[self.df.id == id]

user_dfm = UserDfm({
    "id": [1, 2, 3],
    "username": ["Bessie Bennett", "Sandra Matthews", "Jessie Bates"],
    "profile": ["BLAH BLAH BLAH", "PITH PITH PITH", None]
})

user_dfm.validate()
# : True

user_dfm.find_by_id(1)
# :    id username       profile
# : 0  1  Bessie Bennett BLAH BLAH BLAH

※ 機能的にこれで業務改善するのか検証はできていないので、実戦投入して改善していきたいと思っています。

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?