I'm trying to write the values of an array to a .csv file in python. But when I open the file in excel, the data is shown in one row. I want to have one column where each member of the array is a row.
The array "testLabels" is of the form:
array(['deer', 'airplane', 'dog', ..., 'frog', 'cat', 'truck'],
dtype='<S10')
And the code I use to write to the csv is:
import csv
resultFile = open("/filepath",'wb')
wr = csv.writer(resultFile)
wr.writerows([testLabels])
Any help would be greatly appreciated.
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.
You can save your NumPy arrays to CSV files using the savetxt() function. This function takes a filename and array as arguments and saves the array into CSV format. You must also specify the delimiter; this is the character used to separate each variable in the file, most commonly a comma.
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.
Try this:
wtr = csv.writer(open ('out.csv', 'w'), delimiter=',', lineterminator='\n')
for x in arr : wtr.writerow ([x])
You should change the delimiter. CSV is Comma Separated Value, but Excel understands that a comma is ";" (yeah weird). So you have to add the option delimiter=";", like
csv.writer(myfile, delimiter=";")
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