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
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.
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.
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).
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With