我有一些存储在.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中。
到目前为止我的代码:
导入大熊猫 import 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
上面的代码没有按照我的需要进行操作,看来我无法找到解决问题的方法。有没有人对我如何修复我的代码或采用另一种方法来正确格式化这些数据有任何想法?
由于