【问题标题】:python One hot encoding for comma separated values [closed]python 逗号分隔值的一种热编码[关闭]
【发布时间】:2019-08-13 00:15:40
【问题描述】:

我的数据集是这样的

Type   Date         Issues
M      1 Jan 2019   A12,B56,C78
K      2 May 2019   B56, D90
M      5 Feb 2019   A12,K31 
K      3 Jan 2019   A12,B56,K31,F66
.
.
.

我想为问题栏做一个热编码

所以我的数据集看起来像这样

Type   Date         A12 B56 C78 D90 E88 K31 F66
M      1 Jan 2019   1   1   1   0   0   0   0
K      2 May 2019   0   1   0   1   0   0   0
M      5 Feb 2019   1   0   0   0   0   1   0
K      3 Jan 2019   1   1   0   0   0   1   1
.
.
.

如何在 Python 中做到这一点

【问题讨论】:

  • 你要的不是one-hot编码,我不知道它的正确名称。
  • 请按照您创建此帐户时的建议遵循帮助文档中的发布指南。 On topichow to ask 和 ...the perfect question 在此处申请。 StackOverflow 不是设计、编码、研究或教程资源。但是,如果您遵循您在网上找到的任何资源,进行诚实的编码尝试并遇到问题,那么您将有一个很好的示例可以发布。
  • 我们希望您做出诚实的尝试,而不仅仅是发布您的编码作业。
  • 这是pandas.DataFrame吗?

标签: python one-hot-encoding


【解决方案1】:

使用pandas.Series.str.get_dummies:

import pandas as pd

new_df = pd.concat([df.drop('Issues', 1), df['Issues'].str.get_dummies(sep=",")], 1)
print(new_df)

输出:

  Type        Date   D90  A12  B56  C78  F66  K31  K31 
0    M  1 Jan 2019     0    1    1    1    0    0     0
1    K  2 May 2019     1    0    1    0    0    0     0
2    M  5 Feb 2019     0    1    0    0    0    0     1
3    K  3 Jan 2019     0    1    1    0    1    1     0

【讨论】:

    【解决方案2】:

    假设您的问题被串联成字符串,您可以这样做:

    # Get a list of the issues
    issues = sorted(set(",".join(df.Issues).split(",")))
    
    # Fill columns with 0's and 1's
    for issue in issues:
        df[issue] = df.Issues.str.contains(issue).astype(int)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多