我想创建从值的字典,我从Excel单元格得到的,我的代码如下,
wb = xlrd.open_workbook('foo.xls')
sh = wb.sheet_by_index(2)
for i in range(138):
cell_value_class = sh.cell(i,2).value
cell_value_id = sh.cell(i,0).value
我想创建一个字典,如下图所示,它由来自Excel单元格来的值;
{'class1': 1, 'class2': 3, 'class3': 4, 'classN':N}
我如何能创造这本词典的任何想法?
d = {}
wb = xlrd.open_workbook('foo.xls')
sh = wb.sheet_by_index(2)
for i in range(138):
cell_value_class = sh.cell(i,2).value
cell_value_id = sh.cell(i,0).value
d[cell_value_class] = cell_value_id
或者你可以尝试熊猫
from pandas import *
xls = ExcelFile('path_to_file.xls')
df = xls.parse(xls.sheet_names[0])
print df.to_dict()
该脚本可以让你的Excel数据表转换成词典列表:
import xlrd
workbook = xlrd.open_workbook('foo.xls')
workbook = xlrd.open_workbook('foo.xls', on_demand = True)
worksheet = workbook.sheet_by_index(0)
first_row = [] # The row where we stock the name of the column
for col in range(worksheet.ncols):
first_row.append( worksheet.cell_value(0,col) )
# transform the workbook to a list of dictionaries
data =[]
for row in range(1, worksheet.nrows):
elm = {}
for col in range(worksheet.ncols):
elm[first_row[col]]=worksheet.cell_value(row,col)
data.append(elm)
print data
你可以用熊猫来做到这一点。 进口熊猫和阅读Excel作为一个大熊猫数据帧。
import pandas as pd
file_path = 'path_for_your_input_excel_sheet'
df = pd.read_excel(file_path, encoding='utf-16')
您可以使用pandas.DataFrame.to_dict
到大熊猫数据帧转换成字典。 从这里找到相同的文档
df.to_dict()
这会给你你读Excel工作表的字典。
通用示例:
df = pd.DataFrame({'col1': [1, 2],'col2': [0.5, 0.75]},index=['a', 'b'])
>>> df
col1 col2 a 1 0.50 b 2 0.75
>>> df.to_dict()
{'col1': {'a': 1, 'b': 2}, 'col2': {'a': 0.5, 'b': 0.75}}
我会去:
wb = xlrd.open_workbook('foo.xls')
sh = wb.sheet_by_index(2)
lookup = dict(zip(sh.col_values(2, 0, 138), sh.col_values(0, 0, 138)))
如果你可以把它转换到csv这是非常合适的。
import dataconverters.commas as commas
filename = 'test.csv'
with open(filename) as f:
records, metadata = commas.parse(f)
for row in records:
print 'this is row in dictionary:'+row