简体   繁体   English

使用 pandas 读取 excel 文件并将值存储到 Python dict 中,以列名作为键

[英]Read excel file with pandas and store values into Python dict with the column names as keys

I have following excel:我有以下excel:

type        name          latitude    longitude
--------------------------------------------
area        area1         50.33       4.23
building    building1     -           -

I'm using pandas to read in the excel file using following function:我正在使用 pandas 使用以下函数读取 excel 文件:

def read_excel(self,sheet_name):
    df = pd.read_excel(io=self.excel_file, sheet_name=sheet_name)
    dict = df.to_dict()

I get following output:我得到以下输出:

{
  'type': { 0: 'area', 1: 'building' }, 
  'name': { 0: 'area1', 1: 'building1' }, 
  'latitude': { 0: 50.33, 1: nan }, 
  'longitude': { 0: 4.23, 1: nan }
}

I would like to have the following output:我想要以下输出:

[
    {
         'type': 'area', 
         'name': 'area1',
         'latitude': 50.33, 
         'longitude': 4.23
    }, 
    {
         'type': 'building', 
         'name': 'building1', 
         'latitude': nan, 
         'longitude': nan
    }
]

To achieve this, I have written the following function:为此,我编写了以下函数:

def read_excel(self,sheet_name):
        df = pd.read_excel(io=self.excel_file, sheet_name=sheet_name)
        dict = df.to_dict()

        objects = []

        for i in range(0,len(df.index)):
            temp = {}
            temp['type'] = dict['type'][i]
            temp['name'] = dict['name'][i]
            temp['latitude'] = dict['latitude'][i]
            temp['longitude'] = dict['longitude'][i]
            objects.append(temp)

        print(objects)

This produces the output I want.这会产生我想要的输出。 However, I would like to have a solution that is more dynamic, eg that I don't need create a temp dict with assigning statically column names.但是,我想要一个更动态的解决方案,例如,我不需要创建一个带有静态分配列名的临时字典。

Any suggestions to achieve this?有什么建议可以实现这一目标吗?

pass orient='records' to to_json :)orient='records'传递给to_json :)

always refer to the documentation as a debugging step!始终将文档作为调试步骤! https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.to_dict.html https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.to_dict.html

您是否尝试将其定位为records

print(df.to_dict(orient='records'))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 从文件中读取数据,存储在python dict中并在python中搜索值 - read data from file, store in a python dict and search for values in python 使用dict键作为列名写入CSV文件 - Writing to a CSV file with dict keys as column names 将字典值增量添加到pandas DataFrame。 具有dict键的列名称的DataFrame - Incremental addition of dictionary values to a pandas DataFrame. DataFrame with column names of dict keys Python Pandas将字典键映射到值 - Python pandas map dict keys to values 如何在将 dict 转换为 pandas DataFrame 时设置列标题(其中列名与 dict 键不匹配)? - How to set column headers while converting dict to pandas DataFrame (where column names do not match dict keys)? 熊猫:读取xlsx文件以Column1作为键和column2作为值进行字典 - pandas :Read xlsx file to dict with column1 as key and column2 as values 使用唯一列值作为键转换Pandas Dataframe to_dict() - Convert Pandas Dataframe to_dict() with unique column values as keys Pandas Dataframe to_dict()以唯一列值作为键 - Pandas Dataframe to_dict() with unique column values as keys 如何读取csv文件中包含的python字典并将数据存储在pandas数据框中? - How can i read a python dict contained in a csv file and store the data in a pandas dataframe? Python从文件中读取字符串,并将其拆分为列名和值 - Python read in string from file and split it into column names and values
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM