0

So I am having trouble writing my data to a .csv file using the import csv package. My data is stored in the following general format:

[(Time, [[ID#, MAG, Merr], [ID#, MAG, Merr]])]

An example of my data set is shown below:

data = [(24.23, [[1.0, 18.116, 0.062], [2.0, 18.236, 0.063], [3.0, 17.855, 0.063]]),
       (25.67, [[1.0, 17.968, 0.044], [2.0, 18.189, 0.051], [3.0, 17.757, 0.048]]),
       (26.89, [[1.0, 17.634, 0.025], [2.0, 17.781, 0.029], [3.0, 17.454, 0.026]])]

I wanted to write this data into a .csv file that would look like this:

24.23,  1.0,  18.116,  0.062,  2.0,  18.236,  0.063,  3.0,  17.855,  0.063
25.67,  1.0,  17.968,  0.044,  2.0,  18.189,  0.051,  3.0,  17.757,  0.048
28.89,  1.0,  17.634,  0.025,  2.0,  17.781,  0.029,  3.0,  17.454,  0.026

I tried the following:

import csv
with open('myfile.csv', 'w') as f:
        w = csv.writer(f, dialect = 'excel-tab')
        w.writerows(data)

But I got tons of brackets in the results. I was wondering if there was a better way to approach this?

2 Answers 2

3

You should flatten the the list first before writing it to csv file.

with open('myfile.csv', 'w') as f:
        w = csv.writer(f, dialect='excel-tab') # use `delimiter=','` for ',' in file
        for item in data:
            lst = [item[0]] + [y for x in item[1] for y in x]
            w.writerow(lst)
Sign up to request clarification or add additional context in comments.

Comments

0

Well, you can always just manually unpack your data:

data = [[a, b, c, d, e, f, g, h, i, j] for a, [[b,c,d],[e,f,g],[h,i,j]] in data]

...or there are lots of other answers on SO on how to flatten your data (eg. here)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.