Convert a NumPy array into a CSV using file handling
File handling operations might be the easiest way to convert a NumPy array to a CSV file.
In Python, the str.format function is used to format strings. It inserts one or more replacement fields and placeholders, denoted by a pair of curly braces {}, into a string. The values supplied to the format function are inserted into these placeholders, resulting in a new string that includes the original input string and the formatted values.
The with keyword in Python is used in file handling operations. It ensures that the file is properly closed after it is no longer needed. This is particularly useful when writing to a CSV file, as it helps to prevent data corruption or loss. Here’s an example:
Example
Python3
# import numpy library import numpy # create an array a = numpy.array([[ 1 , 6 , 4 ], [ 2 , 4 , 8 ], [ 3 , 9 , 1 ], [ 11 , 23 , 43 ]]) # save array into csv file rows = [ "{},{},{}" . format (i, j, k) for i, j, k in a] text = "\n" .join(rows) with open ( 'data3.csv' , 'w' ) as f: f.write(text) |
Output:
Also Read: How to Read CSV Files with NumPy?
Convert a NumPy array into a CSV file
After completing your data science or data analysis project, you might want to save the data or share it with others. Exporting a NumPy array to a CSV file is the most common way of sharing data.
CSV file format is the easiest and most useful format for storing data and is convenient to share with others. So in this tutorial, we will see different methods to convert a NumPy array into a CSV file.
Different methods to convert a NumPy array to a CSV file are:
- Using DataFrame.to_csv() method
- Using NumPy_array.tofile() method
- Using NumPy.savetxt() method
- Using File Handling operations
Let’s understand these methods better with examples.