LoginSignup
22
17

More than 3 years have passed since last update.

pandasのDataFrameのapplyで複数列を返す。

Last updated at Posted at 2020-12-21

pandasのDataFrameのapplyで複数列を返す場合のサンプルです。

apply で  result_type='expand' を指定します。(バージョン0.23以上)

以下はpandas.DataFrame.applyより

result_type{‘expand’, ‘reduce’, ‘broadcast’, None}, default None
これらは、axis = 1(列)の場合にのみ機能します。
「expand」:リストのような結果が列に変換されます。
「reduce」:リストのような結果を展開するのではなく、可能であればシリーズを返します。 これは「expand」の反対です。
「ブロードキャスト」:結果はDataFrameの元の形状にブロードキャストされ、元のインデックスと列が保持されます。
デフォルトの動作(なし)は、適用された関数の戻り値によって異なります。リストのような結果は、それらの一連の結果として返されます。 ただし、apply関数がSeriesを返す場合、これらは列に展開されます。

バージョン0.23.0の新機能。

テストデータ

import pandas as pd 
dt={
    "x"  :[1100 , 1200 , 1300 ]  ,
    "y"  :[2100 , 2200 , 2300 ]  ,
    }

df=pd.DataFrame(dt)
print(df.to_markdown())
x y
0 1100 2100
1 1200 2200
2 1300 2300

サンプルソース


def fnc(x):
    return x["x"]+1,x["x"]+2 

df[["a","b"]]=df.apply(lambda x:fnc(x),axis=1, result_type='expand')
print(df.to_markdown())
x y a b
0 1100 2100 1101 1102
1 1200 2200 1201 1202
2 1300 2300 1301 1302

参考

pandas.DataFrame.apply

22
17
4

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
22
17