• sklearn快速入门教程:独热编码


    1. import pandas as pd
    2. data = pd.read_csv(r"D:\本科\kaggle数据挖掘\titanic\train.csv", index_col = 0)
    3. data.head()

     处理缺失值:

    1. from sklearn.impute import SimpleImputer
    2. Embarked = data.loc[:, "Embarked"].values.reshape(-1,1)
    3. imp_mode = SimpleImputer(strategy = "most_frequent") #most_frequent == 众数
    4. data.loc[:,"Embarked"] = imp_mode.fit_transform(Embarked)
    5. data.info()

     

    
    Int64Index: 891 entries, 1 to 891
    Data columns (total 4 columns):
     #   Column      Non-Null Count  Dtype 
    ---  ------      --------------  ----- 
     0   Survived    891 non-null    int64 
     1   Sex         891 non-null    object
     2   Embarked    891 non-null    object
     3   Survived.1  891 non-null    int64 
    dtypes: int64(2), object(2)
    memory usage: 34.8+ KB
    1. from sklearn.preprocessing import OneHotEncoder
    2. X = data.iloc[:,0:-1]
    3. X

     

    1. enc = OneHotEncoder(categories = 'auto').fit(X) #categories是自动属性——不用人为输入有什么属性(男、女),自动识别
    2. result = enc.transform(X).toarray() #to array 转化成array
    3. result
    array([[0., 1., 0., 0., 1.],
           [1., 0., 1., 0., 0.],
           [1., 0., 0., 0., 1.],
           ...,
           [1., 0., 0., 0., 1.],
           [0., 1., 1., 0., 0.],
           [0., 1., 0., 1., 0.]])
    
    result.shape #查看result的shape
    (891, 5)

    891行,5列(3+2:

    男:10

    女:01

    S:100

    C:010

    Q:001

    1. result = pd.DataFrame(result)
    2. result

    1. newdata = pd.concat([X,result], axis = 1)
    2. newdata.head()

     

    1. newdata.drop(["Sex", "Embarked"], axis = 1, inplace = True) #删除掉Sex和Embarked列
    2. newdata.columns = ["Female", "Male", "Embarked_C", "Embarked_Q", "Embarked_S"]
    3. newdata.head()

  • 相关阅读:
    protobuf 存取数据
    文件上传漏洞详解
    【云原生】· 一文了解docker中的网络
    在Cloudreve网盘系统中集成kkFileView在线预览(暂时)
    【vue】全局组件
    axios详解
    UWB定位系统源码
    记一次栈溢出异常问题的排查
    k8s日常动手实践 ~~ pod访问 pod请求 k8s api ~ 含新版带curl的busybox镜像
    MySQL基础(DDL、DML、DQL)
  • 原文地址:https://blog.csdn.net/ykrsgs/article/details/126327990