Python 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 in Python.

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.

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 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,

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

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 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,

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

Output:

That’s all about Python Array to CSV.


import_contacts

You may also like:

Related Posts

  • Make requirements.txt in Python
    03 May

    Make requirements.txt in python

    Table of ContentsWhat is the requirements.txt file in Python?Ways to make requirements.txt file in PythonUsing the pip to make requirements.txt in PythonUsing the conda command to make requirements.txt file in PythonUsing the pipreqs package to make requirements.txt file in PythonConclusion What is the requirements.txt file in Python? Every package is also updated regularly and features […]

  • Create an array of 1 to 10 in Python
    03 May

    Create an Array of 1 to 10 in Python

    Table of ContentsIntroductionHow to create an array of 1 to 10 in Python?Using the range() function to create an array of 1 to 10 in Python.Using list comprehension along with the range() function to create an array of 1 to 10 in Python.Using a user-defined function to create an array of 1 to 10 in […]

  • Remove Urls from String in Python
    03 May

    Remove Urls from Text in Python

    Table of ContentsIntroductionWays to remove URLs from Text in PythonUsing the re.sub() function to remove URLs from Text in PythonUsing the re.findall() function to remove URLs from Text in PythonUsing the re.search() function to remove URLs from Text in PythonUsing the urllib.urlparse class to remove URLs from Text in PythonConclusion In this post, we will […]

  • Create a list from 1 to 100 in Python
    03 May

    Create a List from 1 to 100 in Python

    Table of ContentsWays to create a list from 1 to 100 in PythonUsing the range() function to create a list from 1 to 100 in PythonUsing the numpy.arange() function to create a list from 1 to 100 in PythonUsing the for loop with range() to create a list from 1 to 100 in PythonConclusion In […]

  • Return vs Print in Python
    16 April

    Return vs Print in Python

    Table of ContentsReturn vs Print in PythonConclusion Return vs Print in Python In Python, we work with a wide range of functions that make our code simple. We can also create functions using the def keyword. A function can be defined as per our requirement and can display something or return a value. This is […]

  • Floor division in Python
    10 April

    Floor division in Python

    Table of ContentsWhat is Floor Division in Python?How to implement floor division in Python?Using the // operator to implement floor division in Python.Using the // operator to implement floor division on negative integers in Python.Using the // operator to implement floor division on floating-point numbers in Python.Using the // operator to implement floor division with […]

Leave a Reply

Your email address will not be published.

Subscribe to our newletter

Get quality tutorials to your inbox. Subscribe now.