Domanda

I have a very simple (I think) question but can't find the answer. I'm used to R where creating and manipulating datasets is really straight forward. I'm writing a python code that generates 3 lists of values like the following:

names = [control, control, control, vinc, vinc, vinc] area = [20.3, 23.4, 24.5, 65.45, 76.45, 34.65] mean = [123, 232, 132, 65, 34, 65]

I would like to output these lists as one csv file where each list is a column:

names, area, mean control, 20.3, 123 control, 23.4, 232 control, 24.5, 132 vinc, 65.45, 65 vinc, 76.45, 34 vinc, 34.65, 65

It can't be really difficult to do this but I can't find the way.

Any idea?? Thanks!!

È stato utile?

Soluzione

Use zip function and csv module:

import csv

names = ['control', 'control', 'control', 'vinc', 'vinc', 'vinc']
area = [20.3, 23.4, 24.5, 65.45, 76.45, 34.65]
mean = [123, 232, 132, 65, 34, 65]

op_file = open('output', 'w')
csv_writer = csv.writer(op_file, delimiter=',')
csv_writer.writerow(['names', 'area', 'mean']) #print the header
for row in zip(names, area, mean):
    csv_writer.writerow(row) # write each row by zipping the three lists
op_file.close()

Altri suggerimenti

Unless you save the list names somewhere i can't think of a way to automatically write the list's name in the file.

So assuming that, what you need is to open a file for non binary writing:

f=open('test.csv','w')

then write each line string by string including the carriage returns:

f.write('names area mean \n')
for i in range(len(names)):
    f.write(names[i]+', '+str(area[i])+', '+str(mean[i])+ '\n')

This should create what you need.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top