如何从Excel中检索数据并在Python中格式化?

我试图从Excel中检索数据,并将它们放入以下格式在Python中:

dataset={ 'User A': {'Lady in the Water': 2.5, 'Snakes on a Plane': 3.5, 'Just My Luck': 3.0, 'Superman Returns': 3.5, 'You, Me and Dupree': 2.5, 'The Night Listener': 3.0}, 'Gene Seymour': {'Lady in the Water': 3.0, 'Snakes on a Plane': 3.5, 'Just My Luck': 1.5, 'Superman Returns': 5.0, 'You, Me and Dupree': 3.5, 'The Night Listener': 3.0 }} 

在哪里的Excel文件看起来像

  User A User B Lady in the Water 2.5 3 Snakes on a Plane 3.5 3.5 Just My Luck 3 1.5 Superman Returns 3.5 5 You, Me and Dupree 2.5 3.5 The Night Listener 3 3 

pandas模块使这非常简单:

 import pandas as pd df = pd.read_excel('workbook.xlsx', index_col=0) dataset = df.to_dict() 

在这个代码中, pd.read_excel函数收集来自excel文件的所有数据并将其存储到一个pandas DataFramevariables中。 数据框带有大量非常强大的内置数据重组和操作方法 。 其中一种方法是to_dict ,它在代码中用于将数据转换为嵌套字典。

另一种方式是通过openpyxl:

 from openpyxl import Workbook wb = load_workbook(filename = 'workbook.xlsx') sheet_ranges = wb['cell range'] values = sheet_ranges['cell locations'].values() data = values.to_dict()