A CSV file is a simple text file, with data separated by commas. It can represent tabular data and viewed as spreadsheets.
An array is used to store a collection of elements under a single name. We use the numpy
module to deal with arrays in Python.
We will discuss different methods on how to write array to CSV in Python.
Table of Contents
- Using the pandas.to_csv() function to write Python array to CSV
- Using the numpy.tofile() function to write Python array to CSV
- Using the numpy.savetxt() function to write Python array to CSV
- Using the file-handling methods to write Python array to CSV
- Using the writerows() function to write Python array to CSV
Using the pandas.to_csv()
function to write Python array to CSV
The to_csv()
function exports a pandas
DataFrame to a CSV file of the desired name. We can create a DataFrame using an array and then write this DataFrame to a CSV file.
The advantage of this method is that we can view the DataFrame and check how it looks before exporting it to a CSV file.
See the following code.
1 2 3 4 5 6 |
import pandas as pd import numpy as np arr = np.asarray([ [7,8,9], [5,8,9] ]) pd.DataFrame(arr).to_csv('sample.csv') |
Output:
1 2 3 4 5 |
,0,1,2 0,7,8,9 1,5,8,9 |
In the above example, we were able to save an array in a CSV file. Note that this function automatically adds the column names and the index column to the file.
Numerous parameters can be used with this function. Some of them are discussed below.
- The
sep
parameter is used to set the field delimiter for the file. By default, it is a comma. - The
index_label
can be used to give the column a label, which is to be used as the index. - The
headers
parameter sets the column names for the file. - For floating numbers, we can specify the format using the
float_format
parameter.
We will use some of these parameters in the example below.
1 2 3 4 5 6 |
import pandas as pd import numpy as np arr = np.asarray([ [7,8,9], [5,8,9] ]) pd.DataFrame(arr).to_csv('sample.csv', index_label = "Index", header = ['a','b','c']) |
Output:
1 2 3 4 5 |
Index,a,b,c 0,7,8,9 1,5,8,9 |
In the above example, we added the column names using the header
parameter and also provided the label for the index column using the index_label
parameter.
Using the numpy.tofile()
function to write Python array to CSV
The tofile()
function can write a numpy
array to a binary or text file. It is generally used for quick storage of the data. It also provides the sep
and format
parameter to set the delimiter character and string format. Since we are saving the array in a CSV file, we will need to specify the sep
parameter as a comma.
However, it is not considered a convenient method to export an array to a CSV, because precision is lost while using this method, and everything is stored in a single line.
For example,
1 2 3 4 5 |
import numpy as np arr = np.asarray([ [7,8,9], [5,8,9] ]) arr.tofile('sample.csv', sep = ',') |
Output:
1 2 3 |
7,8,9,5,8,9 |
In the above example, one can observe that the final output in the file is in a single line.
Using the numpy.savetxt()
function to write Python array to CSV
The numpy.savetxt()
function can export an array to a text file. It is generally used only with one or two dimensional arrays and does not give the desired output with higher dimensional arrays. This method provides a lot of parameters to get the final file in CSV format.
- The
delimiter
parameter can be used to provide the character or string to separate the columns. - The
header
parameter is used to write a string at the start of the file. - To write something at the end of the file we use the
footer
parameter. - We can use the
encoding
parameter to encode the final file. - The
fmt
parameter specifies the format for the elements of the array in the file.
In the following example, we will use this function to write array to CSV file.
1 2 3 4 5 |
import numpy as np arr = np.asarray([ [7,8,9], [5,8,9]]) np.savetxt('sample.csv',arr, fmt = '%d', delimiter=",") |
Output:
1 2 3 4 |
7,8,9 5,8,9 |
In the above example, we specified the delimiter character as a comma because the final file needs to be a CSV file. The fmt
parameter was set as %d
because our array contains only integers. Also notice that no columns or indexes are added to the file by default.
Using the file-handling methods to write Python array to CSV
We can create a file object and use it to write array to CSV file. However, it is not advisable to use this method since it requires a lot of memory and can get complicated with large arrays.
For example,
1 2 3 4 5 6 7 8 |
import numpy as np arr = np.asarray([ [7,8,9], [5,8,9]]) rows = ["{},{},{}".format(i, j, k) for i, j, k in arr] text = "\n".join(rows) with open('sample.csv', 'w') as f: f.write(text) |
Output:
1 2 3 4 |
7,8,9 5,8,9 |
In the above example, we first converted the array to a list. Then we joined the elements of the list with a newline character using the join()
function and wrote these elements to a CSV file by creating a file-object using the open()
function.
Using the writerows()
function to write Python array to CSV
The csv
module has classes and methods available to read and read CSV files. We can create a writer
object and use the writerow()
function to write the array to a CSV file. We will also create a file object using the open()
function to be used in the writer()
function.
We can use the delimiter
in the writer()
constructor to specify the separator character.
We will use this method in the following example.
1 2 3 4 5 6 7 8 |
import csv import numpy as np arr = np.asarray([ [7,8,9], [5,8,9]]) with open('sample.csv', 'w') as f: mywriter = csv.writer(f, delimiter=',') mywriter.writerows(arr) |
Output:
1 2 3 4 |
7,8,9 5,8,9 |
That’s all about Python Array to CSV.