【发布时间】:2017-10-10 07:53:49
【问题描述】:
我有一个 .csv 文件,其中包含我想将其中一些列转换为 one-hot 的数据。问题出现在倒数第二行,其中单热索引(例如第一个特征)被放置在所有行中,而不仅仅是我当前所在的行。 我如何访问 2D 列表似乎有些问题……有什么建议吗? 谢谢
def one_hot_encode(data_list, column):
one_hot_list = [[]]
different_elements = []
for row in data_list[1:]: # count different elements
if row[column] not in different_elements:
different_elements.append(row[column])
for i in range(len(different_elements)): # set variable names
one_hot_list[0].append(different_elements[i])
vector = [] # create list shape with zeroes
for i in range(len(different_elements)):
vector.append(0)
for i in range(1460):
one_hot_list.append(vector)
ind_row = 1 # encode 1 for each sample
for row in data_list[1:]:
index = different_elements.index(row[column])
one_hot_list[ind_row][index] = 1 # mistake!! sets all rows to 1
ind_row += 1
【问题讨论】:
-
在第一个
if语句之后还有一个缩进错误。 -
您好,如果以下任何答案解决了您的问题,请点击旁边的复选标记考虑accepting it。这向更广泛的社区表明您已经找到了解决方案,并为回答者和您自己提供了一些声誉。没有义务这样做。
-
我从问题标题中删除了“(已解决)”一词。 (大多数有问题的未来用户不会使用“已解决”一词来搜索他们的问题)。表示您的问题已解决的正确方法是接受其中一个答案 - 请参阅 Lafexlos 评论中的链接。
标签: python arrays list one-hot-encoding