Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Save a numpy array to csv with a string header

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
like image 503
Lucien S. Avatar asked Nov 30 '13 22:11

Lucien S.


People also ask

How do I save a NumPy array to CSV?

Use the numpy. savetxt() Function to Save a NumPy Array in a CSV File. The savetxt() function from the numpy module can save an array to a text file. We can specify the file format, delimiter character, and many other arguments to get the final result in our desired format.

How do I save a NumPy array to a text file?

Let us see how to save a numpy array to a text file. Creating a text file using the in-built open() function and then converting the array into string and writing it into the text file using the write() function. Finally closing the file using close() function.

Can NumPy store strings?

The elements of a NumPy array, or simply an array, are usually numbers, but can also be boolians, strings, or other objects.

How do I store an array in a csv file?

We can write an array to a CSV file by first converting it to a DataFrame and then providing the CSV file's path as the path argument using the Dataframe. to_csv() method. Since the default value of the sep argument is , , we have to provide the DataFrame and the path argument to the Dataframe. to_csv() method.


1 Answers

The header argument (the docs):

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

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

like image 116
cyborg Avatar answered Oct 15 '22 02:10

cyborg