Python Creating Dictionary from excel data

后端 未结 6 763
梦毁少年i
梦毁少年i 2020-11-30 08:48

I want to create a dictionary from the values, i get from excel cells, My code is below,

wb = xlrd.open_workbook(\'foo.xls\')
sh = wb.sheet_by_index(2)   
f         


        
6条回答
  •  悲哀的现实
    2020-11-30 09:44

    You can use Pandas to do this. Import pandas and Read the excel as a pandas dataframe.

    import pandas as pd
    file_path = 'path_for_your_input_excel_sheet'
    df = pd.read_excel(file_path, encoding='utf-16')
    

    You can use pandas.DataFrame.to_dict to convert a pandas dataframe to a dictionary. Find the documentation for the same here

    df.to_dict()
    

    This would give you a dictionary of the excel sheet you read.

    Generic Example :

    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}}

提交回复
热议问题