Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Save multiple arrays to a csv file with column names

As simple as it seems, I could not find any solution for my question online. Basically, I have two arrays a and b that 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.

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

Name1 Name2
 1     5
 2     6
 3     7
 4     8

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

Edit: Arrays

like image 417
Koba Avatar asked Nov 03 '15 05:11

Koba


People also ask

How do I import only certain columns from a CSV file?

This can be done with the help of the pandas. read_csv() method. We will pass the first parameter as the CSV file and the second parameter the list of specific columns in the keyword usecols. It will return the data of the CSV file of specific columns.

How many columns can CSV handle?

csv files have a limit of 32,767 characters per cell. Excel has a limit of 1,048,576 rows and 16,384 columns per sheet. CSV files can hold many more rows. You can read more about these limits and others from this Microsoft support article here.

How do I append a column to an existing csv file?

Open your CSV file in append mode Create a file object for this file. Pass the file object and a list of column names to DictWriter() You will get an object of DictWriter. Pass the dictionary as an argument to the writerow() function of DictWriter (it will add a new row to the CSV file).


1 Answers

You can do it with pandas package easily:

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)
like image 52
Anton Protopopov Avatar answered Oct 23 '22 11:10

Anton Protopopov