python - 使用数字和分类缩放数据框
问题描述
我在 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)
解决方案
缩放/标准化仅适用于数字列。对于分类列,还有其他可用的技术,例如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
希望这能给你一些想法。
推荐阅读
- ios - WKWebView is not displaying Images
- python - xpath get following siblings from current up to a certain point
- python - 如何根据变化的条件匹配 DataFrame 列上的值?
- bash - shell ,单行 if 语句,变量赋值错误
- html - 如何淡化背景滤镜模糊的边缘
- javascript - 如何将数组中的字符串转换为类?
- python - 创建一个返回给定基数的整数的函数
- hadoop - 安装 Impala
- git - 如何根据终端中的当前分支更新代码窗口?
- c++ - 为 Xcode 设置 C++ SFML 时出现错误:“原因:找不到图像”