Python discrete feature encoding

Source: Internet
Author: User

There are two kinds of discrete feature coding, which have the meaning of size and character.

1, the characteristic does not have the size significance direct single-heat code

2, the characteristics of the size of the significance of the use of mapping code

[Python]View PlainCopy
  1. Import Pandas as PD
  2. DF = PD. DataFrame ([
  3. [' green ', ' M ', 10.1, ' Label1 '],
  4. [' Red ', ' L ', 13.5, ' Label2 '],
  5. [' Blue ', ' XL ', 15.3, ' Label2 ']]
  6. # color, label does not have size meaning, size has significance
  7. Df.columns = [' color ', ' size ', ' length ', ' label ']
  8. Df

[Python]View PlainCopy
  1. Size_mapping = {
  2. ' XL ': 3,
  3. ' L ': 2,
  4. ' M ': 1}
  5. df[' size ' = df[' size '].map (size_mapping)
  6. label_mapping = {Lab:idx for Idx,lab in enumerate (set (df[' label '))}
  7. df[' label '] = df[' label '].map (label_mapping)
  8. Df

Direct use of functions for single-hot coding

does not differentiate whether it has a size meaning

[Python]View PlainCopy
  1. Import Pandas as PD
  2. DF = PD. DataFrame ([
  3. [' green ', ' M ', 10.1, ' Label1 '],
  4. [' Red ', ' L ', 13.5, ' Label2 '],
  5. [' Blue ', ' XL ', 15.3, ' Label2 ']]
  6. # color, label does not have size meaning, size has significance
  7. Df.columns = [' color ', ' size ', ' length ', ' label ']
  8. Pd.get_dummies (DF)

Get_dummies usage:

[Python]View PlainCopy
    1. Import Pandas as PD
    2. s = PD. Series (List (' ABCA '))
    3. Pd.get_dummies (s)

[Python]View PlainCopy
    1. DF = PD. DataFrame ({' a ': [' a ', ' B ', ' a '], ' B ': [' B ', ' a ', ' C '],
    2. ' C ': [1, 2, 3]}
[Python]View PlainCopy
    1. Pd.get_dummies (DF, prefix=[' col1 ', ' col2 '])

Python discrete feature encoding

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.