简体   繁体   中英

Problems with importing list of data from python to csv

I've just started using python, and I have some problems with exporting a list of data from python to csv.

I have some array of values, and each value corresponds to a specific time. What I want is copying these arrays (all have the same length) on a csv so that each row presents the value of all the variables for that specific instant of time. What I've written is:

with open ('Risultati.csv', 'w', newline='' ) as f:
    thewriter=csv.writer(f)
    
    thewriter.writerow(['x','y','z','w'])
    for i in range(0,len(x)):
        thewriter.writerow(['x[%i]', 'y[%i]','z[%i]','w[%i]'])

but in the csv I've obtained in each row is x[%i] y[%i] z[%i] w[%i] . I also would like that each list of values appears aligned with the header, like in a table with Excel.

I hope I made myself clear. Thank you in advance.

What about the following:

import csv
import random

x = random.sample(range(10, 30), 5)
y = random.sample(range(10, 30), 5)
z = random.sample(range(10, 30), 5)
w = random.sample(range(10, 30), 5)

with open ('out.csv', 'w', newline='' ) as f:
    thewriter=csv.writer(f)

    thewriter.writerow(['x','y','z','w'])
    for i in range(0,len(x)):
        thewriter.writerow([x[i], y[i], z[i], w[i]])

Gives you:

$ python3 ./test.py
$ cat ./out.csv
x,y,z,w
18,23,17,25
23,27,16,26
15,18,28,10
12,15,23,18
26,29,21,27

I would strongly recommend you read a tutorial on python lists, There are many out there, for example this one

Wouldn't it be possible to create pandas Dataframe and then save it to file at once? Small example below:

import pandas as pd

# buffer for data
values = []
# here adding exemplary rows
values.append({'x':1, 'y':2, 'z':3, 'w':4})
values.append({'x':4, 'y':5, 'z':6, 'w':7})
# convert to df
df = pd.DataFrame(values)
# save to csv
df.to_csv('file.csv', index=None)

The comment from @urban to the original post seems correct.

Still, I would advise you to take a look at the Pandas library (you will probably be using it at some point anyways). You would only need:

import pandas as pd
df = pd.DataFrame()  # create a new empty DataFrame
df['x'] = x  # fill it with values
df['y'] = y
df['z'] = z
df['w'] = w
df.to_csv('.../file.csv', index=None)

Pandas also lets you use df.to_excel() , df.to_parquet() , and more, to save your output in other file formats.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM