Python 中 ML 训练的字典列表操作

Dictionary List Manipulation for ML Training in Python

我正在使用此代码读取 excel 文件。

from xlrd import open_workbook

book = open_workbook('excel_demo.xlsx')
sheet = book.sheet_by_index(0)

# read header values into the list    
keys = [sheet.cell(0, col_index).value for col_index in  xrange(sheet.ncols)]

dict_list = []
for row_index in xrange(1, sheet.nrows):
  d = {keys[col_index]: sheet.cell(row_index, col_index).value 
     for col_index in xrange(sheet.ncols)}
  dict_list.append(d)

print dict_list

我得到的输出是字典列表的形式,如下所示:

  [{'A': 1.0, 'C': 3.0, 'B': 2.0}, 
  {'A': 5.0, 'C': 7.0, 'B': 6.0}]

就我而言,我需要将此列表作为训练集传递给我的朴素贝叶斯算法。所以我需要如下内容:

train_data = [({"a": 4, "b": 1, "c": 0}, "1:0"),
({"a": 5, "b": 2, "c": 1}, "2:1"),
({"a": 0, "b": 3, "c": 4}, "3:4"),
({"a": 5, "b": 1, "c": 1}, "1:1"),
({"a": 1, "b": 4, "c": 3}, "4:3")]

如何在 python 代码中实现这种转换。在这种情况下,正则表达式会有所帮助吗?非常感谢。

让 l 成为你的原始 Excel 数据

t = [(r, "".join((str(r['B']),":",str(r['C'])))) for r in l]

t 会给你你描述的输出。

试试这条线

[({k.lower(): d[k]  for k in d},':'.join(str(d['A']), str(d['B']))) 
 for d in dict_list]