gpt4 book ai didi

python - 对多列混合数据进行一次热编码

转载 作者:行者123 更新时间:2023-12-01 09:27:04 26 4
gpt4 key购买 nike

我有一个混合类型的数据集,需要将其转换为数字,同时仍保留字符类型数据的信息。我当前的解决方案是使用 R 语言,但我现在需要将其转换为 Python,因为接收此脚本的人不知道或不想过渡到学习 R,这是可以理解的。是否可以使用 Pandas 库在 Python 中实现此目的?如果是这样,如何实现这一目标?

library(data.table)
library(stringr)

dat <- data.table(x = c('No Data', '2', 'Testing', 'Offline'),
y = c('2', 'No Data', '4', 'Testing'),
z = c(1, 2, 3, 6))

select_cols <- c('x','y')

dat[, paste0(select_cols,'_no_data') := lapply(.SD, function(x) as.numeric(str_detect(x, 'No Data'))), .SDcols = select_cols]
dat[, paste0(select_cols,'_offline') := lapply(.SD, function(x) as.numeric(str_detect(x, 'Offline'))), .SDcols = select_cols]
dat[, paste0(select_cols,'_testing') := lapply(.SD, function(x) as.numeric(str_detect(x, 'Testing'))), .SDcols = select_cols]

dat[, paste0(select_cols) := lapply(.SD, function(x) str_replace(x, 'No Data|Offline|Testing', '0')), .SDcols = select_cols]
dat[, paste0(select_cols) := lapply(.SD, function(x) as.numeric(x)), .SDcols = select_cols]

dat

编辑:打印原始数据和预处理数据

 x        y          z 
No Data 2 1
2 No Data 2
Testing 4 3
Offline Testing 6

x    y    z   x_no_data   y_no_data   x_offline   y_offline   x_testing   y_testing  
0 2 1 1 0 0 0 0 0
2 0 2 0 1 0 0 0 0
0 4 3 0 0 0 0 1 0
0 0 6 0 0 1 0 0 1

最佳答案

这是一个解决方案,它的主要部分是 pd.get_dummies ,它为您进行 one-hot 编码,以及 pd.to_numeric()带有参数 errors = "coerce" 的方法会按照您想要的方式更改原始 xy 列。

步骤是:

1) 使用 pd.get_dummies 创建虚拟列,仅适用于您要编码的列为数字的行。例如,这是通过 pd.get_dummies(df.x.loc[~df.x.str.isnumeric()], prefix='x') 实现的

2) join带有原始数据框的虚拟列

3) 强制原始 xy 为数字类型,如果不可能,则使用 NaN,最后用 0 替换 NaN

df = pd.DataFrame({'x':['No Data', '2', 'Testing', 'Offline'],
'y':['2', 'No Data', '4', 'Testing'],
'z':[1, 2, 3, 6]})
# Steps 1 and 2
df = (df.join(pd.get_dummies(df.x.loc[~df.x.str.isnumeric()],
prefix='x'))
.join((pd.get_dummies(df.y.loc[~df.y.str.isnumeric()], prefix='y')))
.fillna(0))

# Step 3
df['x'] = pd.to_numeric(df.x, errors='coerce').fillna(0)
df['y'] = pd.to_numeric(df.y, errors='coerce').fillna(0)

# output:
x y z x_No Data x_Offline x_Testing y_No Data y_Testing
0 0.0 2.0 1 1.0 0.0 0.0 0.0 0.0
1 2.0 0.0 2 0.0 0.0 0.0 1.0 0.0
2 0.0 4.0 3 0.0 0.0 1.0 0.0 0.0
3 0.0 0.0 6 0.0 1.0 0.0 0.0 1.0

关于python - 对多列混合数据进行一次热编码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50298293/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com