【问题标题】:One hot encoding for ages categorical data年龄分类数据的一种热编码
【发布时间】:2019-07-17 19:05:45
【问题描述】:

当尝试使用一个热编码器对以下类别实施编码时,我收到了couldn't convert string to float 错误。

['0-17', '55+', '26-35', '46-50', '51-55', '36-45', '18-25']

【问题讨论】:

  • 55 出现两次。)如果没有您使用的代码,很难推荐要更改的内容。

标签: python-3.x sklearn-pandas one-hot-encoding


【解决方案1】:

我做了一些真正快速的东西,应该可以工作。你会看到我有一个看起来很讨厌的单线来预先调整你的限制;但是,如果您只是将限制直接转换为正确的格式,将会容易得多。

本质上,这只是遍历限制列表并与限制进行比较。如果数据样本小于限制,我们将该索引设为 1 并中断。

import random

# str_limits = ['0-17', '55+', '26-35', '46-50', '51-55', '36-45', '18-25']
#
# oneline conditioning for the limit string format
# limits = sorted(list(filter(lambda x: not x.endswith("+"), map(lambda v: v.split("-")[-1], str_limits))))
# limits.append('1000')

# do this instead
limits = sorted([17, 35, 50, 55, 45, 25, 1000])

# sample 100 random datapoints between 0 and 65 for testing
samples = [random.choice(list(range(65))) for i in range(100)]

onehot = []  # this is where we will store our one-hot encodings
for sample in samples:
    row = [0]*len(limits)  # preallocating a list
    for i, limit in enumerate(limits):
        if sample <= limit:
            row[i] = 1
            break

    # storing that sample's onehot into a onehot list of lists
    onehot.append(row)

for i in range(10):
    print("{}: {}".format(onehot[i], samples[i]))

我不确定您的实现细节,但您可能在某些时候忘记将字符串转换为整数。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-03-06
    • 2020-10-08
    • 2016-05-08
    • 2018-12-17
    • 2021-01-16
    • 2020-09-25
    • 2020-09-12
    • 2019-06-18
    相关资源
    最近更新 更多