Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Writing array to csv python (one column)

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.

like image 806
user3240210 Avatar asked Jan 30 '14 19:01

user3240210


People also ask

How do I write an array in CSV?

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.

How will you save an array of numbers in .CSV format?

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.

How do I convert a NumPy array to a CSV File in Python?

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.


2 Answers

Try this:

wtr = csv.writer(open ('out.csv', 'w'), delimiter=',', lineterminator='\n')
for x in arr : wtr.writerow ([x])
like image 70
deostroll Avatar answered Oct 19 '22 23:10

deostroll


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=";")
like image 33
MatthieuBizien Avatar answered Oct 20 '22 00:10

MatthieuBizien