0
1

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 3 years have passed since last update.

カテゴリーデータを数値データに変換する

Posted at

1. はじめに

文字で与えられるカテゴリーデータを数値データに変換するやり方の一例として、指定した数字に置き換える方法、カテゴリーのカウント数に置き換える方法、についてメモしておきます。

2. ライブラリ、データを読み込む

データ例として、KaggleのTitanicデータを使用します。

import numpy as np
import pandas as pd

train = pd.read_csv("./input/train.csv")
test = pd.read_csv("./input/test.csv")
data0 = pd.concat([train, test], sort=False)
data0.columns

#  Index(['PassengerId', 'Survived', 'Pclass', 'Name', 'Sex', 'Age', 'SibSp',
#         'Parch', 'Ticket', 'Fare', 'Cabin', 'Embarked'], dtype='object')

3. 空欄(nan)を埋める

'Embarked'のデータで変換してみます。

data0['Embarked'][0:6]

#   0    S
#   1    C
#   2    S
#   3    S
#   4    S
#   5    Q
#    Name: Embarked, dtype: object
#文字データの種類を調べる
data0['Embarked'].unique()

#array(['S', 'C', 'Q', nan], dtype=object)
#nanを数える
data0['Embarked'].isnull().sum()

#2
#文字データをカウントする(before)
v0 = data0["Embarked"].value_counts()
v0

#    S    914
#    C    270
#    Q    123
#    Name: Embarked, dtype: int64
#nanを'S'で埋める
data0['Embarked'].fillna(('S'), inplace=True)
#文字データをカウントする(after)
v1 = data0["Embarked"].value_counts()
v1

#    S    916
#    C    270
#    Q    123
#    Name: Embarked, dtype: int64

4-1. 文字データを指定した数字に置き換える

data = data0
v2 = { 'S':0, 'C':1, 'Q':2 }
data['Embarked_1'] = data['Embarked'].map(v2)
data['Embarked_1'][0:6]

#    0    0
#    1    1
#    2    0
#    3    0
#    4    0
#    5    2
#    Name: Embarked_map, dtype: int64

4-2. 文字データをカウント数に置き換える

data=data0
vc = data['Embarked'].value_counts()
vc

#    S    916
#    C    270
#    Q    123
#    Name: Embarked, dtype: int64
data['Embarked_2'] = data['Embarked'].map(vc)
data['Embarked_2'][0:6]

#    0    916
#    1    270
#    2    916
#    3    916
#    4    916
#    5    123
#    Name: Embarked_count, dtype: int64
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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?