環境
python3.8.10
pandas 1.3.5
やりたいこと
どのような関数を使うかは別として、複数列使って新しい列を作りたい。
やり方
まず、簡単にテーブルを作る。
import pandas as pd
def test(c1, c2):
return c1 + c2
df = pd.DataFrame([['a', 'b'], ['c', 'd']], columns=['char1', 'char2'])
以下のやり方で複数列を使用できる。
df['concat_text'] = df[['char1', 'char2']].apply(lambda text: test(text[0], text[1]), axis=1)
-
apply()
は関数をDataFrameに対して適用するメソッドであり、内部のlambda式は簡単に関数を作ることができるものである。 - lambda式で定義した変数を他の関数に引数として渡し、その結果を新しい列に格納する。
- 元となるDataFrameのカラムの順番通りに0オリジンでオフセットを指定する。
- axisで行方向と列方向のどちらに関数を適用するかを決める。デフォルトは0なので明示的に指定する。