Pandas でカテゴリ変数を数値に変換する方法
次の基本構文を使用して、pandas DataFrame のカテゴリ変数を数値変数に変換できます。
df[' column_name '] = pd. factorize (df[' column_name '])[0]
次の構文を使用して、DataFrame 内の各カテゴリ変数を数値変数に変換することもできます。
#identify all categorical variables cat_columns = df. select_dtypes ([' object ']). columns #convert all categorical variables to numeric df[cat_columns] = df[cat_columns]. apply ( lambda x: pd.factorize (x)[ 0 ])
次の例は、この構文を実際に使用する方法を示しています。
例 1: カテゴリ変数を数値に変換する
次のパンダ データフレームがあるとします。
import pandas as pd #createDataFrame df = pd. DataFrame ({' team ': ['A', 'A', 'A', 'B', 'B', 'B', 'C', 'C', 'C'], ' position ': ['G', 'G', 'F', 'G', 'F', 'C', 'G', 'F', 'C'], ' points ': [5, 7, 7, 9, 12, 9, 9, 4, 13], ' rebounds ': [11, 8, 10, 6, 6, 5, 9, 12, 10]}) #view DataFrame df team position points rebounds 0 A G 5 11 1 A G 7 8 2 A F 7 10 3 B G 9 6 4 B F 12 6 5 B C 9 5 6 C G 9 9 7 C F 4 12 8 C C 13 10
次の構文を使用して、「チーム」列を数値に変換できます。
#convert 'team' column to numeric
df[' team '] = pd. factorize (df[' team '])[ 0 ]
#view updated DataFrame
df
team position points rebounds
0 0 G 5 11
1 0 G 7 8
2 0 F 7 10
3 1 G 9 6
4 1 F 12 6
5 1 C 9 5
6 2 G 9 9
7 2 F 4 12
8 2 C 13 10
変換の様子は次のとおりです。
- 「 A 」の値を持つ各チームは0に変換されました。
- 「 B 」の値を持つ各チームは1に変換されました。
- 「 C 」の値を持つ各チームは2に変換されました。
例 2: 複数のカテゴリ変数を数値に変換する
もう一度、次の pandas DataFrame があると仮定してみましょう。
import pandas as pd #createDataFrame df = pd. DataFrame ({' team ': ['A', 'A', 'A', 'B', 'B', 'B', 'C', 'C', 'C'], ' position ': ['G', 'G', 'F', 'G', 'F', 'C', 'G', 'F', 'C'], ' points ': [5, 7, 7, 9, 12, 9, 9, 4, 13], ' rebounds ': [11, 8, 10, 6, 6, 5, 9, 12, 10]}) #view DataFrame df team position points rebounds 0 A G 5 11 1 A G 7 8 2 A F 7 10 3 B G 9 6 4 B F 12 6 5 B C 9 5 6 C G 9 9 7 C F 4 12 8 C C 13 10
次の構文を使用して、DataFrame 内の各カテゴリ変数を数値変数に変換できます。
#get all categorical columns
cat_columns = df. select_dtypes ([' object ']). columns
#convert all categorical columns to numeric
df[cat_columns] = df[cat_columns]. apply ( lambda x: pd.factorize (x)[ 0 ])
#view updated DataFrame
df
team position points rebounds
0 0 0 5 11
1 0 0 7 8
2 0 1 7 10
3 1 0 9 6
4 1 1 12 6
5 1 2 9 5
6 2 0 9 9
7 2 1 4 12
8 2 2 13 10
2 つのカテゴリ列 (チームとポジション) は両方とも数値に変換されていますが、ポイントとリバウンドの列は同じままであることに注意してください。
注: pandasactorize()関数の完全なドキュメントはここで見つけることができます。
追加リソース
次のチュートリアルでは、パンダで他の一般的な操作を実行する方法を説明します。
Pandas DataFrame 列を文字列に変換する方法
Pandas DataFrame 列を整数に変換する方法
Pandas DataFrame で文字列を float に変換する方法