【问题标题】:How to put every line of a excel table into a python dictionary?如何将excel表格的每一行放入python字典?
【发布时间】:2022-11-10 23:14:36
【问题描述】:

刚开始使用python并从事一个小项目。 试图找出 Excel 文件中每一行的字典列表。

例如:

first_name last_name age
Peter Johnsen 42
Mark Conner 32
Susanna Rock 36

进入:

[
{'first_name' : 'Peter' , 'last_name' : 'Johnsen' , 'age' : '42'} ,
{'first_name' : 'Mark' , 'last_name' : 'Conner' , 'age' : '32'} ,
{'first_name' : 'Susanna' , 'last_name' : 'Rock' , 'age' : '36'} ,
]

我想为我的 excel 文件获取一本字典,但这样我就可以为每一列获取一本字典。

import pandas as pd

data = 'person.xlsx'

df = pd.read_excel(data)

df_dict = df.to_dict()

print(df_dict)
{
'first_name' : {0: 'Peter' , 1 : 'Mark' , 2 : 'Susanna'} ,
'last_name' : {0: 'Johnsen' , 1 : 'Conner' , 2 : 'Rock'} ,
'age' : {0: '42' , 1 : '32' , 2 : '36'} ,
}

我怎样才能转换字典,或者有没有办法像从一开始就希望拥有的那样正确地获取字典?

非常感谢。

最大的

【问题讨论】:

    标签: python excel pandas dictionary


    【解决方案1】:

    这是一种方法

    # to_dict with orientation as records
    out=df.to_dict('records')
    out
    
    [{'first_name': 'Peter ', 'last_name': 'Johnsen ', 'age': 42},
     {'first_name': 'Mark ', 'last_name': 'Conner ', 'age': 32},
     {'first_name': 'Susanna ', 'last_name': 'Rock ', 'age': 36}]
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-09-30
      • 2023-03-19
      • 1970-01-01
      • 2016-03-14
      • 2019-02-19
      相关资源
      最近更新 更多