自动将数据从Python字典写入一个非常特定的excel表单

2024-04-20 14:04:04 发布

您现在位置:Python中文网/ 问答频道 /正文

我将一些数据存储在一个.csv文件中,该文件会自动读入一个嵌套的python字典。我已经拥有的代码将读取任何格式正确的文件,这样字典的形式就是dict[experiment][variable]=value。你知道吗

我的目标是将数据重写为非常特定的格式,即:

Name    Experiment1                     
Notes                           
Componentnotes                          
Components  time    LR1R2   LR1R2_I    R1       R1_I       R2      R2_I
Values       0     1.69127  16.9127    271.087  2710.87    127.087  1270.87
            20     62.0374  356.28     146.54   2107.15    2.54022  667.147
            40     50.0965  451.149    146.061  1793.54    2.06075  353.535

请注意,这是从excel粘贴的,因此Experiment1位于单元格B2中。你知道吗

到目前为止我的代码是:

进口熊猫 导入openpyxl

def write_experiment_files_template(self):
    alphabet=list(string.ascii_lowercase)#get alphabet for looping over later
    for i in self.child_experiments_dir: #loop over all locations for writing the properly formatted data  
        for j in self.data_dct.keys(): #loop over experiments
            name = j[:-4] #get name of experiment and use it as name in spreadsheet
            for k in self.data_dct[j].keys():
                components= self.data_dct[j][k].keys() #get variable names
                data_shape =self.data_dct[j][k].shape  #get dimentions of data (which is a pandas data frame)
                #write the easy bits into the excel workbook
                wb = openpyxl.Workbook()
                ws = wb.active
                ws['A1']='Name'
                ws['B1']=name
                ws['A2']='Notes'
                ws['A3']='Componentnotes'
                ws['A4']='Components'
                ws['B4']='time'
                ws['A5']='Values'
                #loop over variables and write the pandas data frame into the space for the values
                for l in range(len(components)):
                    ws[alphabet[l+2]+'4']=components[l] #plus 2 to account for time and headers
                    #loop over the space in the spreadsheet required for data input (B5:B35)
                    for m in ws[alphabet[l+2]+'5':alphabet[len(components)+1]+str(data_shape[0]+4)]:
                        m[0]= self.data_dct[j] #attempt to assign values

上面的代码没有做我需要它,似乎我找不到一个方法来修复它。有人对我如何修复代码或采取其他方法来正确格式化这些数据有什么想法吗?你知道吗

谢谢


Tags: the数据代码nameinselfloopfor