使用数字和分类缩放数据框

may*_*aaa 0 python python-3.x pandas scikit-learn

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

     subject_id  |   pH       |  urinecolor |  blood pressure  
     --------------------------------------------------------                
        3        |  1.00      |  red        |  high
        3        |  1.15      |  red        |  high
        4        |  2.00      |  yellow     |  low
Run Code Online (Sandbox Code Playgroud)

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

    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)
Run Code Online (Sandbox Code Playgroud)

YOL*_*OLO 5

缩放/标准化仅适用于数字列。对于分类列,还有其他可用的技术label encoding,例如one 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
Run Code Online (Sandbox Code Playgroud)

希望这能给您一些想法。