首页 > 解决方案 > 使用数字和分类缩放数据框

问题描述

我在 python 中,我有包含两个数字的数据框,如下所示

     subject_id  |   pH       |  urinecolor |  blood pressure  
     --------------------------------------------------------                
        3        |  1.00      |  red        |  high
        3        |  1.15      |  red        |  high
        4        |  2.00      |  yellow     |  low

和明确的。我想缩放和规范化数据框,但传统缩放给出错误无法缩放字符串我尝试以下操作,但它给了我作为列表的返回,我想缩放列并返回整个数据框以进行进一步的步骤,任何人都可以帮助我那。提前致谢

    df= pd.readcsv()
    dfTest =df.select_dtypes(include='number')
    scaler = StandardScaler(copy=True, with_mean=True, with_std=True)
    dftest= df.select_dtypes(include=np.number)
    X = scaler.fit_transform(dftest)

标签: pythonpython-3.xpandasscikit-learn

解决方案


缩放/标准化仅适用于数字列。对于分类列,还有其他可用的技术,例如label encodingone hot encoding。这是您可以执行的操作:

from sklearn.preprocessing import StandardScaler

sc = StandardScaler()

# get numeric data
num_d = d.select_dtypes(exclude=['object'])

# update the cols with their normalized values
d[num_d.columns] = sc.fit_transform(num_d)

# convert string variable to One Hot Encoding
d = pd.get_dummies(d)

   subject_id        pH  urinecolor_red  urinecolor_yellow
0   -0.707107 -0.870563               1                  0
1   -0.707107 -0.529908               1                  0
2    1.414214  1.400471               0                  1

希望这能给你一些想法。


推荐阅读