Help us understand the problem. What is going on with this article?

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

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

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

encoding.py
import pandas as pd
df = pd.DataFrame([
    ['green','M',10.1,'class1'],
    ['red','L',13.5,'class2'],
    ['blue','XL',15.3,'class1']    
])

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

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

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     1   10.1           0
# 1    red     2   13.5           1
# 2   blue     3   15.3           0
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
No comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
ユーザーは見つかりませんでした