【问题标题】:scaling data-frame with numeric and categorical使用数字和分类缩放数据框
【发布时间】:2020-04-19 14:57:18
【问题描述】:

我在 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)

【问题讨论】:

  • 一些数据有助于了解您在做什么以及正在发生什么。
  • 另外,您可以自己进行标准化。求均值 df['col1'].mean() 并求标准差 df['col1'].std()。您的标准化数据将是 df['norm_col1']= (df['col1']-df['col1'].mean())/df['col1'].std()
  • 我正在使用示例数据集对其进行编辑

标签: python python-3.x pandas scikit-learn


【解决方案1】:

缩放/标准化仅适用于数字列。对于分类列,还有其他可用的技术,例如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

希望这能给你一些想法。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-08-29
    • 2020-03-09
    • 1970-01-01
    • 1970-01-01
    • 2013-08-30
    相关资源
    最近更新 更多