Save a numpy array to csv with a string header
Asked Answered
B

1

11

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
Bunkum answered 30/11, 2013 at 22:56 Comment(0)
C
18

The header argument (the docs):

numpy.savetxt(fname, X, delimiter=' ', header='')

But you may prefer Pandas if you are actually dealing with a table.

Chinn answered 30/11, 2013 at 23:55 Comment(2)
I am indeed dealing with a 2d array, this is why I believed the 'header' attribute wouldn't work. I'll try panda! Cheers!Bunkum
To save current fields as headers: np.savetxt(path, X, delimiter=',', header= ','.join(X.dtype.names))Wisnicki

© 2022 - 2024 — McMap. All rights reserved.