LoginSignup
0
1

More than 1 year has passed since last update.

pandasでクラスラベルを整数にエンコーディングする方法

Last updated at Posted at 2019-08-17
  1. やりたいこと
    任意のクラスラベル(ここではclass1,class2)を整数に変換をしたい
    class1 => 0
    class2 => 1

  2. pandasデータフレーム定義

encoding.py
import pandas as pd
df = pd.DataFrame(
    {'color':['green','red','blue'],
    'size':['M','L','X'],
    'price':[10.0,12.0,15.3],
     'classlabel':['class1', 'class2', 'class1']
    }
)

2.エンコーディング前のデータフレーム

print(df)
#   color  size  price  classlabel
# 0  green   M   10.1      class1
# 1    red   L   13.5      class2
# 2   blue   X   15.3      class1

3.エンコーディング実行

import numpy as np
class_mapping = {label:idx for idx, label in enumerate(np.unique(df['classlabel']))}

df['classlabel'] = df['classlabel'].map(class_mapping)

4.エンコーディング後

print(df)
#   color  size  price  classlabel
# 0  green   M   10.1      1
# 1    red   L   13.5      2
# 2   blue   X   15.3      1
0
1
0

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
0
1