LoginSignup
3
4

More than 1 year has passed since last update.

DataFrameの一括処理の時にpartialを使うと便利だった

Posted at

概要

  • pythonのfunctools.partialの宣伝
  • 引数の一部を固定した新たな関数が作れる
  • DataFrameにmapで一括処理する時に便利だった

partialとは

関数 partial() は、関数の位置引数・キーワード引数の一部を「凍結」した部分適用として使われ、簡素化された引数形式をもった新たなオブジェクトを作り出します。例えば、 partial() を使って base 引数のデフォルトが 2 である int() 関数のように振る舞う呼び出し可能オブジェクトを作ることができます:

引数の一部を固定して新たな関数を作れるということらしい。

from functools import partial

# ベースとなる関数
def linear(x, a, b):
    """ y = ax + b """
    return a * x + b

# y = 2x となる関数doubleを作る
double = partial(linear, a=2, b=0)
print(double(5)) # -> 10

# y = x + 3 となる関数offset3を作る
offset3 = partial(linear, a=1, b=3)
print(offset3(5)) # -> 8

便利だった使い方

  • DataFrameの複数の列に類似した処理を適応するときに便利だった
def word_repeat(base, repeat=1):
    """ 単語を繰り返したい """
    return base * repeat

#[ ['a', 'b', 'c'],
#  ['d', 'e', 'f'],
#  ['g', 'h', 'i'] ]
test_str = np.array(['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h','i']).reshape(3,3)
df = pd.DataFrame(test_str)

# 1列目は1回、2列目は2回、3列目は3回繰り返す
df[0]=list(map(partial(word_repeat, repeat=1), df[0]))
df[1]=list(map(partial(word_repeat, repeat=2), df[1]))
df[2]=list(map(partial(word_repeat, repeat=3), df[2]))


#[ ['a', 'bb', 'ccc'],
#  ['d', 'ee', 'fff'],
#  ['g', 'hh', 'iii'] ]
print(df)

まとめ

partialを使用すると引数の一部を固定した新たな関数が作成できる。
DataFrameにmapで一括処理する時に便利だった。
他にも良い使い方があったら教えてplease。

以上

3
4
1

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
4