Skip to main content
 首页 » 编程设计

python之如何从 excel 中检索数据并在 python 中格式化它们

2025年05月04日25itcoder

我正在尝试从 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 中 DataFrame多变的。数据框带有大量非常强大的 built-in methods for data reorganization and manipulation .其中一种方法是 to_dict,它在此处的代码中用于将数据转换为嵌套字典。