LoginSignup
49
39

More than 5 years have passed since last update.

pandasのapplyに複数の引数を持つ関数を与える

Posted at

どういうこと?

以下のような状況のとき、

import pandas as pd
df = pd.DataFrame({'x': [1, 2, 3, 4], 'y': ['A', 'B', 'C', 'D']})

def f1(a, b):
    return a * b

def f2(a, b, c):
    return a * b * c

f1f2apply で列に適用したいということです。

どうすれば?

公式pandas.Series.applyリファレンス の Examples を見ればOKです。

あえて上記の例にあてはめると次のようになります。

2引数の関数をSeriesへ与える場合

args にタプルで追加の引数を与えます。

df.x.apply(f1, args=(2,))

または、 apply にキーワード引数で与えます。

df.x.apply(f1, b=2)

出力は

0    2
1    4
2    6
3    8
Name: x, dtype: int64

引数が3つの場合

この場合も同様です。

df.x.apply(f2, args=(2, 3))
# または
df.x.apply(f2, b=2, c=3)

出力は

0     6
1    12
2    18
3    24
Name: x, dtype: int64

各列へ一度に適用する場合

df.apply(f1, args=(2,))
# または
df.apply(f1, b=2)

出力

   x   y
0  2  AA
1  4  BB
2  6  CC
3  8  DD
49
39
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
49
39