Save a numpy array to csv with a string header
22,583
The header
argument (the docs):
numpy.savetxt(fname, X, delimiter=' ', header='')
But you may prefer Pandas if you are actually dealing with a table.
Author by
Lucien S.
Updated on July 12, 2022Comments
-
Lucien S. almost 2 years
I have a large-ish numpy array containing floats, which I save as a csv file with np.savetxt("myFile.csv", myArray, delimiter=",")
Now, as the array has many columns and it can become hard to remember what is what, I want to add a string header to the array before exporting it. Since numpy doesn't accept strings in float arrays, is there a trick to accomplish this?
[Solution] Thanks to Cyborg's advice, I managed to make this work installing Pandas.
import pandas as pd df = pd.DataFrame(A) # A is a numpy 2d array df.to_excel("A.xls", header=C,index=False) # C is a list of string corresponding to the title of each column of A
-
Lucien S. over 10 yearsI am indeed dealing with a 2d array, this is why I believed the 'header' attribute wouldn't work. I'll try panda! Cheers!
-
mins over 3 yearsTo save current fields as headers:
np.savetxt(path, X, delimiter=',', header= ','.join(X.dtype.names))