【问题标题】:Creating a dictionary from Excel in every sheet在每个工作表中从 Excel 创建字典
【发布时间】:2022-11-10 23:31:21
【问题描述】:

我想根据从 Excel 单元格中获得的值创建一个字典。

这是我的 Excel 电子表格:

我对字典的期望是这样的:

{'Ancolmekar': array([ 3. , 20. ,  6. , ...,  0.5,  0.5,  0.5]),
 'Cidurian': array([0.5, 0.5, 0.5, ..., 0.5, 0.5, 6. ]),
 'Dayeuhkolot': array([0.5, 0.5, 0.5, ..., 5.5, 1.5, 0.5]),
 'Hantap': array([ 1.5, 17.5,  3. , ...,  0.5,  5. ,  1.5]),
 'Kertasari': array([ 1.5,  2.5,  0.5, ...,  1.5, 10. ,  1.5]),
 'Meteolembang': array([ 0.5,  0.5,  0.5, ...,  0.5,  0.5, 10.5]),
 'Sapan': array([ 0.5,  0.5,  6. , ...,  0.5, 13.5, 24. ])}

对代码有任何想法吗?

我的代码是这样的:

# Read Excel data
xl = pd.read_excel('export_3.xlsx')
contoh = pd.read_excel('export_3.xlsx', header=None, sheet_name='EPA BINER')
contoh1 = pd.read_excel('export_3.xlsx', header=None, sheet_name='EPA')
contoh2 = pd.read_excel('export_3.xlsx', header=None, sheet_name='SHORT BINER')
contoh3 = pd.read_excel('export_3.xlsx', header=None, sheet_name='SHORT EPA')
contoh4 = pd.read_excel('export_3.xlsx', header=None, sheet_name='LONG BINER')
contoh5 = pd.read_excel('export_3.xlsx', header=None, sheet_name='LONG EPA')

总行数为 43824。

【问题讨论】:

    标签: python arrays pandas


    【解决方案1】:

    我想你可以选择:

    path = 'export_3.xlsx'
    file = pd.ExcelFile(path)
    sheets = file.sheet_names
    
    for sheet in sheets:
        sheet_dict = {}
        contoh = pd.read_excel(path,  sheet_name=sheet)
        for col in contoh.columns:
            sheet_dict[col] = list(contoh[col])
        print(sheet_dict, "
    
    
    ")
        
    

    这样,您的 Excel 中的每张纸都有一个字典,如果需要,您可以将其存储在 for 循环之前声明的列表中。

    而不是使用list(contoh[col]) 我想你也可以使用np.array(list(contoh[col]))

    【讨论】:

      【解决方案2】:

      转置df,将每行中的所有列值组合到列表中并打印/保存为具有列方向的json 根据您的要求使用类似的方法。

      contoh = pd.read_excel('export_3.xlsx',header=None,sheet_name='EPA BINER')
      df = contoh.transpose()
      df['new'] = df.values.tolist()
      df = df['new']
      df.to_json(orient = 'columns')
      

      【讨论】:

        猜你喜欢
        • 2021-06-20
        • 2019-04-23
        • 1970-01-01
        • 2021-11-06
        • 2013-06-07
        • 1970-01-01
        • 2020-12-23
        • 1970-01-01
        • 2021-06-10
        相关资源
        最近更新 更多