【问题标题】:I am trying to perform one hot encoding for a three sets of data我正在尝试对三组数据执行一次热编码
【发布时间】:2021-06-28 04:37:57
【问题描述】:

我有一个列表(长度=228),它代表列的标签(即 column.head)。此外,我有三个样本(a、b、c),对于每个样本,我必须创建one-hot 编码。这个怎么做。结果可能看起来像一个矩阵,其中包含 o 和一个值,维度为 (3,228)

a='95', '66', '137', '70', '20'
b='36', '66', '44', '214', '105', '133'
c='170', '66', '97', '153', '105', '138'
lnew=list(range(1,229))
lnew=list(map(str, total_labels))
print(lnew)

【问题讨论】:

  • 是否允许您使用 sklearn,或者您是否被要求从头开始执行此操作? thecleverprogrammer.com/2020/08/27/…
  • @NewCoder18 我无法做到这一点,我尝试创建一个大小为z=np. zeros(3,228) 的空数组。然后我尝试将值分配给z[0,0]=a,但出现错误。你有什么建议吗?

标签: python pandas list one-hot-encoding


【解决方案1】:

您创建一个名为矩阵的列表,并为每一行添加子列表,如果索引匹配 0,则为 1

a=[95, 66, 137, 70, 20]
b=[36, 66, 44, 214, 105, 133]
c=[170, 66, 97, 153, 105, 138]

matrice=[]
matrice.append([1 if i in a else 0 for i in range(229)])
matrice.append([1 if i in b else 0 for i in range(229)])
matrice.append([1 if i in c else 0 for i in range(229)])

【讨论】:

    【解决方案2】:

    你可以试试:

    a=[95, 66, 137, 70, 20]
    b=[36, 66, 44, 214, 105, 133]
    c=[170, 66, 97, 153, 105, 138]
    
    df = pd.DataFrame()
    count=0
    for j in [a,b,c]:
        col = [1 if i in j else 0 for i in range(229)]
        df[count] = col
        count+=1
    mat = np.matrix(df).reshape(3,228)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-12-27
      • 1970-01-01
      • 2018-04-28
      • 2018-01-04
      • 2021-11-16
      • 2017-05-02
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多