Python 使用列名将多个数组保存到一个 csv 文件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/33492260/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 13:27:00  来源:igfitidea点击:

Save multiple arrays to a csv file with column names

pythonarrayscsvnumpy

提问by Koba

As simple as it seems, I could not find any solution for my question online. Basically, I have two arrays aand bthat I want to save to a csv file. It will be two columns. I want to add the column names as well. Below code I use to dump arrays to a csv.

看起来很简单,但我在网上找不到任何针对我的问题的解决方案。基本上,我有两个数组ab我要保存到一个CSV文件。它将是两列。我也想添加列名。下面的代码我用来将数组转储到 csv。

from np import array, savetxt

a = array([1,2,3,4])
b = array([5,6,7,8])
savetxt('submission2.csv', zip(a,b), delimiter=',', fmt='%f')

How would I add column names? I would like the csv file to look like

我将如何添加列名?我希望 csv 文件看起来像

Name1 Name2
 1     5
 2     6
 3     7
 4     8

It is so strange that this option is not in the savetxtfunction. headeroption does do it because it just pastes a comment into the first cell. Thanks.

奇怪的是,savetxt函数中没有这个选项。headeroption 这样做是因为它只是将注释粘贴到第一个单元格中。谢谢。

Edit: Arrays

编辑:数组

采纳答案by Burhan Khalid

Use the headeroption, like this:

使用该header选项,如下所示:

>>> import numpy
>>> a = numpy.array([[1,2],[3,4],[5,6]])
>>> numpy.savetxt("foo.csv", a, delimiter=',', header="A,B", comments="")

The resulting file looks like this:

生成的文件如下所示:

A,B
1.000000000000000000e+00,2.000000000000000000e+00
3.000000000000000000e+00,4.000000000000000000e+00
5.000000000000000000e+00,6.000000000000000000e+00

回答by Hackaholic

you can do like this:

你可以这样做:

import np import array, savetxt

a = array([1,2,3,4])
b = array([5,6,7,8])
f = open("submission2.csv", "w")
f.write("{},{}\n".format("Name1", "Name2"))
for x in zip(a, b):
    f.write("{},{}\n".format(x[0], x[1]))
f.close()

回答by Anton Protopopov

You can do it with pandas package easily:

您可以使用pandas包轻松完成:

import pandas as pd
import numpy as np

a = np.array([1,2,3,4])
b = np.array([5,6,7,8])

df = pd.DataFrame({"name1" : a, "name2" : b})
df.to_csv("submission2.csv", index=False)

回答by zeroth

Note that savetxt(and loadtxt) also takes file handles.

请注意,savetxt(和loadtxt) 也接受文件句柄。

Hence if you want a more advanced header you can do this:

因此,如果你想要一个更高级的标题,你可以这样做:

a = array([1,2,3,4])
b = array([5,6,7,8])
with open('submission2.csv','w') as f:
    f.write('# This is a very complex header\n')
    f.write('A,B\n')
    savetxt(f, zip(a,b), delimiter=',', fmt='%f')

Or, as has already been noted, use the header=str(...)argument.

或者,正如已经指出的,使用header=str(...)参数。

回答by Dawid

I have found a solution for saving multiple numpy 1D arrays as columns:

我找到了将多个 numpy 一维数组保存为列的解决方案:

 import numpy as np
 data = []
 for i in single_np_arrays:
     data.append(i)
 data = np.array(data).T  #transpose the array to have proper columns
 np.savetxt('columns_from_np_arrays.csv',data,delimiter=',')