1
1

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 1 year has passed since last update.

Pandas: データフレームについて--07: パイプ

Last updated at Posted at 2022-06-21

パイプ

関数型言語では,データ処理のときに関数を入れ子にすることで中間結果(変数)を明示しないというやり方が,ある意味普通である。

1. 入れ子式に関数を呼ぶ場合

import pandas as pd
df = pd.DataFrame({
    'a': [1, 2, 3, 4, 5],
    'b': [1.2, 3.4, 5.6, 7.8, 9.0]
})
df

def func1(df):
  return df.transform('sqrt')

def func2(df, power=2, constant=1):
  return df.transform(lambda x: x**power + constant)
print(func2(func1(df)))
     a     b
0  2.0   2.2
1  3.0   4.4
2  4.0   6.6
3  5.0   8.8
4  6.0  10.0

2. パイプで順次関数を呼ぶ場合

これに対し,パイプは一つの関数の結果を次の関数の入力にするというように,あたかも「関数をパイプで繋ぐ」ように記述できるため,一部で人気(R など?)。Python でもできるが,効果の程は?

pipe(func: 'Callable[..., T] | tuple[Callable[..., T], str]', *args, **kwargs)
df.pipe(func1).pipe(func2, power=3, constant=5).pipe(print)
           a          b
0   6.000000   6.314534
1   7.828427  11.269290
2  10.196152  18.252019
3  13.000000  26.784214
4  16.180340  32.000000

以下のように書いたほうがわかりやすい場合もある。

(df.pipe(func1)
    .pipe(func2, power=3, constant=5)
    .pipe(print)
)
           a          b
0   6.000000   6.314534
1   7.828427  11.269290
2  10.196152  18.252019
3  13.000000  26.784214
4  16.180340  32.000000

3. もっと知りたい人

help(df.pipe) # Help on method pipe in module pandas.core.generic
1
1
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
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?