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
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.
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.
The elements of a NumPy array, or simply an array, are usually numbers, but can also be boolians, strings, or other objects.
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.
The header
argument (the docs):
numpy.savetxt(fname, X, delimiter=' ', header='')
But you may prefer Pandas if you are actually dealing with a table.
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