1. Home
  2. Docs
  3. Python
  4. Pandas
  5. 文字分類轉數字代號

文字分類轉數字代號

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    #!/usr/bin/env python
    # -*- coding=utf-8 -*-
    # pip install seaborn
    __author__ = "柯博文老師 Powen Ko, www.powenko.com"
      
    import xlrd
    import xlwt
     
    import pandas as pd
     
      
     
    #read data
    df = pd.read_csv('adult.csv')
     
    print(df.head())
    print(df.columns)
    print(df.index)
    print(df.columns)
      
    columnsName=['B','D','F','G','H','I','J','N','O']
     
    for x in columnsName:
        df[x+'_Code'] = df[x].astype("category").cat.codes
     
    #df['Spectral_Class_Code'] = df['Spectral_Class'].astype("category").cat.codes
     
    print(df.head())
     
    df.to_excel("adult.xlsx")