Python write array to CSV

Write array to CSV in Python

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 file.

Using the pandas.to_csv() function to write array to CSV file

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.

Output:

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.

Output:

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 array to CSV file

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,

Output:

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 array to CSV file

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.

Output:

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 array to CSV file

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,

Output:

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 array to CSV file

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.

Output:

That’s all about Python write array to CSV.

Related Posts

  • Python add commas to number
    11 September

    Python add commas to number

    Table of ContentsUsing the format() function to add commas to numbers in PythonUsing the fstrings to add commas to numbers in PythonUsing the regular expressions to add commas to numbers in PythonUsing the locale module to add commas to numbers in Python Python allows us to format values to get the final result in our […]

  • Multiply in Python
    30 August

    Multiply in Python

    Table of ContentsMultiply operator in PythonMultiplying a string with an integerMultiplying all the elements of a listUse the for loop to multiply all the elements of a listUse the functools.reduce() function to multiply all the elements of a listUse the numpy.prod() function to multiply all the elements of a listUse the math.prod() function to multiply […]

  • Auto clicker in Python
    30 August

    How to make auto clicker in Python

    Table of ContentsUsing the pynput module to create an auto clickerUsing the pyautogui module to create an auto clickerUsing the pywin32 (winauto32api) module to create an auto clicker Python has inbuilt modules and methods which allow it to detect and perform keyboard and mouse inputs. We can create an auto-mouse clicker in Python. An auto-clicker […]

  • Iterate through files in directory in Python
    30 August

    Iterate through files in directory in python

    Table of ContentsUsing the os.scandir() function to iterate through files in a given directory in Python.Using the os.listdir() function to iterate through files in a given directory in Python.Using the os.walk() function to iterate through files in a given directory in Python.Using the pathlib module to iterate through files in a given directory in Python.Using […]

  • Write variable to file in Python
    30 August

    Write variable to file in python

    Table of ContentsUsing the str() functionUsing the repr() functionUsing the string formattingUsing the pickle.dump() functionUsing the numpy.savetxt function File handling is an important concept of programming. Python allows us to read and write content to an external file. In this article, we will discuss several ways to write variable to file in Python. First, let […]

  • Inverse matrix in Python
    24 August

    Inverse matrix in python

    Table of ContentsUsing the Gauss-Jordan method to find the inverse of a given matrix in Python.Using the numpy.linalg.inv() function to find the inverse of a given matrix in Python. The inverse of a matrix in simple mathematics can be defined as a matrix, which when multiplied by the original matrix, gives out the Identity matrix. […]

Leave a Reply

Your email address will not be published. Required fields are marked *

Subscribe to our newletter

Get quality tutorials to your inbox. Subscribe now.