3
3

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] DataFrameの複数列を使って新しい列を作る方法

Posted at

環境

python3.8.10
pandas 1.3.5

やりたいこと

スクリーンショット 2023-03-07 18.16.51.png
これを
スクリーンショット 2023-03-07 18.17.19.png

どのような関数を使うかは別として、複数列使って新しい列を作りたい。

やり方

まず、簡単にテーブルを作る。

import pandas as pd

def test(c1, c2):
    return c1 + c2

df = pd.DataFrame([['a', 'b'], ['c', 'd']], columns=['char1', 'char2'])

スクリーンショット 2023-03-07 18.16.51.png

以下のやり方で複数列を使用できる。

df['concat_text'] = df[['char1', 'char2']].apply(lambda text: test(text[0], text[1]), axis=1)

スクリーンショット 2023-03-07 18.17.19.png

  • apply()は関数をDataFrameに対して適用するメソッドであり、内部のlambda式は簡単に関数を作ることができるものである。
  • lambda式で定義した変数を他の関数に引数として渡し、その結果を新しい列に格納する。
  • 元となるDataFrameのカラムの順番通りに0オリジンでオフセットを指定する。
  • axisで行方向と列方向のどちらに関数を適用するかを決める。デフォルトは0なので明示的に指定する。
3
3
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
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?