Home > database >  How to make a duplicate column in list?
How to make a duplicate column in list?

Time:12-10

I want to create a 2-dimensional list with some lists repeating as many inputs. I tried the following code:

input_exp = 3
experiments = list()
experiments.append(('Experiments', 'Split', 'Batch', 'Training Time'*input_exp, 'Testing Time', 'Loss', 'Accuracy', 'Mean Accuracy'))

df = pd.DataFrame(experiments)
writer = pd.ExcelWriter('Resume.xlsx', engine='xlsxwriter')
df.to_excel(writer, sheet_name='resume', index=False)
writer.save()

input_exp is the number of experiments that I will do. So, if I'm going to experiment two times, then I'll enter input_exp= 2. But after I put the result into excel, it looks like this:

exp 1

Here's what I want to achieve: enter image description here

CodePudding user response:

If you want one list element per string, then you need extend, not append:

input_exp = 3
exp.extend(['Experiments', 'Split', 'Batch']   (['Training Time']*input_exp)   ['Testing Time', 'Loss', Accuracy', 'Mean Accuracy'])

CodePudding user response:

Does this meet the solution you are looking for.

input_exp = 3
exp = []
exp.extend(['Experiments', 'Split', 'Batch', 'Testing Time', 'Loss', 'Accuracy', 'Mean Accuracy', ['Training Time' for i in range(input_exp)]])

output :-

['Experiments', 'Split', 'Batch', 'Testing Time', 'Loss', 'Accuracy', 'Mean Accuracy', ['Training Time', 'Training Time', 'Training Time']]

CodePudding user response:

Try building the list in several parts, using python's [foo]*N idiom to generate an N-list of foo:

input_exp = 3
exp.append(['Experiments', 'Split', 'Batch']   ['Training Time']*input_exp    ['Testing Time', 'Loss', 'Accuracy', 'Mean Accuracy'])

Assuming your original exp contained ['foo', 'bar'] the result will be

['foo',
 'bar',
 ['Experiments',
  'Split',
  'Batch',
  'Training Time',
  'Training Time',
  'Training Time',
  'Testing Time',
  'Loss',
  'Accuracy',
  'Mean Accuracy']]

If you don't want the nested list-inside-of-list use extend in place of append:

exp = ['foo', 'bar']
exp.extend(['Experiments', 'Split', 'Batch']   ['Training Time']*input_exp    ['Testing Time', 'Loss', 'Accuracy', 'Mean Accuracy'])

which results in

['foo',
 'bar',
 'Experiments',
 'Split',
 'Batch',
 'Training Time',
 'Training Time',
 'Training Time',
 'Testing Time',
 'Loss',
 'Accuracy',
 'Mean Accuracy']

CodePudding user response:

As an alternative, you can use chain to glue together as many lists as you need.

from itertools import chain

input_exp = 3
pre_training = ['Experiments', 'Split', 'Batch']
post_training = ['Testing Time', 'Loss', 'Accuracy', 'Mean Accuracy']
run = list(chain(pre_training, ['Training Time'] * input_exp, post_training))

Outputs:

>>> run
['Experiments', 'Split', 'Batch', 'Training Time', 'Training Time', 'Training Time', 'Testing Time', 'Loss', 'Accuracy', 'Mean Accuracy']
  • Related