gpt4 book ai didi

python - 我如何在一个单元格中使用多个值进行一次热编码?

转载 作者:太空宇宙 更新时间:2023-11-04 06:54:44 25 4
gpt4 key购买 nike

我在 Excel 中有这个表格:

id  class
0 2 3
1 1 3
2 3 5

现在,我想用 Python 进行“特殊”的单热编码。对于第一个表中的每个 id,都有两个数字。每个数字对应一个类别(class1、class2 等)。第二个表是基于第一个表创建的,这样对于每个 id,其行中的每个数字都显示在其对应的类列中,而其他列只得到零。例如,id 0 的数字是 2 和 3。2 放在 class2 中,3 放在 class3 中。类 1、4 和 5 获得默认值 0。结果应如下所示:

id  class1  class2  class3  class4  class5
0 0 2 3 0 0
1 1 0 3 0 0
2 0 0 3 0 5

我以前的解决方案,

foo = lambda x: pd.Series([i for i in x.split()])
result=onehot['hotel'].apply(foo)
result.columns=['class1','class2']
pd.get_dummies(result, prefix='class', columns=['class1','class2'])

结果:

    class_1 class_2 class_3 class_3 class_5
0 0.0 1.0 0.0 1.0 0.0
1 1.0 0.0 0.0 1.0 0.0
2 0.0 0.0 1.0 0.0 1.0

(class_3 出现了两次)。我该怎么做才能解决这个问题? (经过这一步,我可以把它转换成我想要的最终格式。)

最佳答案

您需要将变量设置为 categorical然后你可以使用 one hot encoding如图:

In [18]: df1 = pd.DataFrame({"class":pd.Series(['2','1','3']).astype('category',categories=['1','2','3','4','5'])})

In [19]: df2 = pd.DataFrame({"class":pd.Series(['3','3','5']).astype('category',categories=['1','2','3','4','5'])})

In [20]: df_1 = pd.get_dummies(df1)

In [21]: df_2 = pd.get_dummies(df2)

In [22]: df_1.add(df_2).apply(lambda x: x * [i for i in range(1,len(df_1.columns)+1)], axis = 1).astype(int).rename_axis('id')
Out[22]:
class_1 class_2 class_3 class_4 class_5
id
0 0 2 3 0 0
1 1 0 3 0 0
2 0 0 3 0 5

关于python - 我如何在一个单元格中使用多个值进行一次热编码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37646473/

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