0
請查看以下csv文件的前兩行。第一行是字段名稱,第二行是實際數據的第一行。Python For循環迭代未按預期順序
我想遍歷第一行,然後將值以原始順序存儲到數組中。
age workclass fnlwgt education education-num marital-status occupation relationship race sex capital-gain capital-loss hours-per-week native-country label
59 Private 307423 9th 5 Never-married Other-service Not-in-family Black Male 0 0 50 United-States 0
reader = csv.DictReader(csvfile)
train_x = []
train_y = []
dic = {}
for row in reader:
row_x = []
for title in row.keys():
l = ['workclass','education','marital-status','occupation', 'relationship', 'race', 'sex', 'native-country']
if title in l:
value = get_dict[title][row[title]]
row_x.append(value)
elif title == 'label':
train_y.append(float(row['label']))
else:
row_x.append(float(row[title]))
train_x.append(row_x)
這是我得到的第一行:
[3,5,59.0,0.0,0,50.0,4,35,5.0,0.0,如圖8所示,307423.0,4,3]
正如您所看到的,這些字段的排序是錯誤的。 (需要注意的是,美國是35,私屬3 ...)
的CSV行復制在這裏爲方便起見,以及:
age workclass fnlwgt education education-num marital-status occupation relationship race sex capital-gain capital-loss hours-per-week native-country label
59 Private 307423 9th 5 Never-married Other-service Not-in-family Black Male 0 0 50 United-States 0