简体   繁体   English

将数据列表从 python 导入到 csv 时出现问题

[英]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.我刚开始使用 python,在将数据列表从 python 导出到 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.我想要的是在 csv 上复制这些 arrays (都具有相同的长度),以便每一行都显示该特定时刻的所有变量的值。 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] .但是在 csv 中,我在每一行中获得的是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.我还希望每个值列表都与 header 对齐,就像在带有 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我强烈建议您阅读有关 python 列表的教程,那里有很多,例如这个

Wouldn't it be possible to create pandas Dataframe and then save it to file at once?是否可以创建 pandas Dataframe 然后立即将其保存到文件中? 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. @urban 对原始帖子的评论似乎是正确的。

Still, I would advise you to take a look at the Pandas library (you will probably be using it at some point anyways).尽管如此,我还是建议您看一下 Pandas 库(无论如何,您可能会在某个时候使用它)。 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. Pandas 还允许您使用df.to_excel()df.to_parquet()等,将 output 保存为其他文件格式。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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