Label encoding

Làm việc với dữ liệu phân loại trong Python

Kasey Jones

Research Data Scientist

What is label encoding?

The basics:

  • Codes each category as an integer from 0 through n - 1, where n is the number of categories
  • A -1 code is reserved for any missing values
  • Can save on memory
  • Often used in surveys

The drawback:

  • Is not the best encoding method for machine learning (see next lesson)
Làm việc với dữ liệu phân loại trong Python

Creating codes

Convert to categorical and sort by manufacturer name

used_cars['manufacturer_name'] = used_cars['manufacturer_name'].astype("category")

Use .cat.codes

used_cars['manufacturer_code'] = used_cars['manufacturer_name'].cat.codes
Làm việc với dữ liệu phân loại trong Python

Check output

print(used_cars[['manufacturer_name', 'manufacturer_code']])
      manufacturer_name  manufacturer_code
0                Subaru                 45
1                Subaru                 45
2                Subaru                 45
...                 ...                ...
38526          Chrysler                  8
38527          Chrysler                  8
Làm việc với dữ liệu phân loại trong Python

Code books / data dictionaries

An example code book from the American Housing Survey.

1 https://www.census.gov/data-tools/demo/codebook/ahs/ahsdict.html
Làm việc với dữ liệu phân loại trong Python

Creating a code book

codes = used_cars['manufacturer_name'].cat.codes
categories = used_cars['manufacturer_name']
name_map = dict(zip(codes, categories))

print(name_map)
{45: 'Subaru',
 24: 'LADA',
 12: 'Dodge',
 ...
}
Làm việc với dữ liệu phân loại trong Python

Using a code book

Creating the codes:

used_cars['manufacturer_code'] = used_cars['manufacturer_name'].cat.codes

Reverting to previous values:

used_cars['manufacturer_code'].map(name_map)
0        Acura
1        Acura
2        Acura
...
1 https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.map.html
Làm việc với dữ liệu phân loại trong Python

Boolean coding

Find all body types that have "van" in them:

# Code from previous lesson:
used_cars["body_type"].str.contains("van", regex=False)

Create a boolean coding:

used_cars["van_code"] = np.where(
  used_cars["body_type"].str.contains("van", regex=False), 1, 0)

used_cars["van_code"].value_counts()
0    34115
1     4416
Name: van_code, dtype: int64
Làm việc với dữ liệu phân loại trong Python

Encoding practice

Làm việc với dữ liệu phân loại trong Python

Preparing Video For Download...