Pandas: 複数の if else 条件を使用して新しい列を作成する


次の構文を使用すると、複数の if else 条件を使用して pandas DataFrame に新しい列を作成できます。

 #define conditions
conditions = [
    (df[' column1 '] == ' A ') & (df[' column2 '] < 20 ),
    (df[' column1 '] == ' A ') & (df[' column2 '] >= 20 ),
    (df[' column1 '] == ' B ') & (df[' column2 '] < 20 ),
    (df[' column1 '] == ' B ') & (df[' column2 '] >= 20 )
]

#define results
results = [' result1 ', ' result2 ', ' result3 ', ' result4 ']

#create new column based on conditions in column1 and column2
df[' new_column '] = np. select (conditions, results)

この特定の例では、 new_columnという名前の列を作成します。その値は、DataFrame のcolumn1column2の値に基づいています。

次の例は、この構文を実際に使用する方法を示しています。

例: Pandas で複数の If Else 条件を使用して新しい列を作成する

さまざまなバスケットボール選手に関する情報を含む次のパンダ データフレームがあるとします。

 import pandas as pd

#createDataFrame
df = pd. DataFrame ({' team ': ['A', 'A', 'A', 'A', 'B', 'B', 'B', 'B'],
                   ' points ': [15, 18, 22, 24, 12, 17, 20, 28]})

#view DataFrame
print (df)

  team points
0 to 15
1 to 18
2 to 22
3 to 24
4 B 12
5 B 17
6 B 20
7 B 28

ここで、各プレイヤーを次の 4 つのグループのいずれかに分類するclassという新しい列を作成するとします。

  • Bad_Aチームが A でポイント < 20 の場合
  • Good_Aチームが A でポイント ≥ 20 の場合
  • Bad_Bチームが B でポイント < 20 の場合
  • チームが B でポイント ≥ 20 の場合はGood_B

これを行うには、次の構文を使用できます。

 import numpy as np

#define conditions
conditions = [
    (df[' team '] == ' A ') & (df[' points '] < 20 ),
    (df[' team '] == ' A ') & (df[' points '] >= 20 ),
    (df[' team '] == ' B ') & (df[' points '] < 20 ),
    (df[' team '] == ' B ') & (df[' points '] >= 20 )
]

#define results
results = [' Bad_A ', ' Good_A ', ' Bad_B ', ' Good_B ']

#create new column based on conditions in column1 and column2
df[' class '] = np. select (conditions, results)

#view updated DataFrame
print (df)

  team points class
0 A 15 Bad_A
1 A 18 Bad_A
2 A 22 Good_A
3 A 24 Good_A
4 B 12 Bad_B
5 B 17 Bad_B
6 B 20 Good_B
7 B 28 Good_B

クラスという新しい列には、チーム列ポイント列の値に基づいて各プレーヤーのランキングが表示されます。

: NumPy select()関数の完全なドキュメントは、ここで見つけることができます。

追加リソース

次のチュートリアルでは、パンダで他の一般的なタスクを実行する方法を説明します。

Pandas: 条件に基づいてブール列を作成する方法
Pandas: 条件付きで列の値をカウントする方法
パンダ: Groupby を使用して条件付きでカウントする方法

コメントを追加する

メールアドレスが公開されることはありません。 が付いている欄は必須項目です