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

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

I am indeed dealing with a 2d array, this is why I believed the 'header' attribute wouldn't work. I'll try panda! Cheers!
To save current fields as headers: np.savetxt(path, X, delimiter=',', header= ','.join(X.dtype.names))

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.