The Wayback Machine - https://web.archive.org/web/20240918064102/https://www.geeksforgeeks.org/convert-numpy-array-into-csv-file/
Open In App

Convert a NumPy array into a CSV file

Last Updated : 02 Feb, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

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:

  1. Using DataFrame.to_csv() method
  2. Using NumPy_array.tofile() method
  3. Using NumPy.savetxt() method
  4. Using File Handling operations

Let’s understand these methods better with examples.

Convert a NumPy array into a CSV using Dataframe.to_csv()

The DataFrame.to_csv() method is used to write a Dataframe into a CSV file. 

To use DataFrame.to_csv() we have to first convert the NumPy array into pandas DataFrame and then save it to CSV format.

Example

Python3




import pandas as pd
import numpy as np
  
# create a dummy array
arr = np.arange(1,11).reshape(2,5)
print(arr)
  
# convert array into dataframe
DF = pd.DataFrame(arr)
  
# save the dataframe as a csv file
DF.to_csv("data1.csv")


Output:

Convert a NumPy array into a csv file

 

Convert a NumPy array into a CSV using numpy_array.tofile()

This method is used to write a NumPy array into the file. 

The tofile() method allows us to save the NumPy array to a CSV file by calling the function with the NumPy array object and passing the CSV file_name and separator to the function.

Example

Python3




import numpy as np
arr = np.arange(1,11)
print(arr)
  
# use the tofile() method 
# and use ',' as a separator
arr.tofile('data2.csv', sep = ',')


Output:

Convert a NumPy array into a csv file

 

Convert a NumPy array into a CSV using numpy.savetxt()

The numpy.savetxt() method is used to save a NumPy array to a text file.

We can save the NumPy array to a CSV file by passing the file name, NumPy array, and the delimiter in the function numpy.savetxt().

Python3




# import numpy library
import numpy
  
# create an array
a = numpy.array([[1, 6, 4],
                 [2, 4, 8],
                 [3, 9, 1]])
  
# save array into csv file
numpy.savetxt("data3.csv", a, 
              delimiter = ",")


Output:

NumPy array converted into CSV file

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:

Convert a NumPy array into a csv file

Also Read: How to Read CSV Files with NumPy?

Conclusion

Exporting the NumPy array into a CSV file is often required to save or share your data. Python offers many ways to save NumPy arrays into a CSV file. We have discussed four methods to convert a NumPy array into a CSV file. 

In this tutorial, we have explained 4 easy methods to convert a NumPy array into a CSV file with examples and explanations. You can use any method you feel comfortable with.



Similar Reads

How to Convert an image to NumPy array and saveit to CSV file using Python?
Let's see how to Convert an image to NumPy array and then save that array into CSV file in Python? First, we will learn about how to convert an image to a numpy ndarray. There are many methods to convert an image to ndarray, few of them are: Method 1: Using PIL and NumPy library. We will use PIL.Image.open() and numpy.asarray(). Example: C/C++ Code
4 min read
How to create multiple CSV files from existing CSV file using Pandas ?
In this article, we will learn how to create multiple CSV files from existing CSV file using Pandas. When we enter our code into production, we will need to deal with editing our data files. Due to the large size of the data file, we will encounter more problems, so we divided this file into some small files based on some criteria like splitting in
3 min read
Convert HTML table into CSV file in python
CSV file is a Comma Separated Value file that uses a comma to separate values. CSV file is a useful thing in today's world when we are talking about machine learning, data handling, and data visualization. In this article, we will discuss how to convert an HTML table into a CSV file. Converting HTML Table into CSV file in Python Example: Suppose HT
2 min read
How to convert CSV File to PDF File using Python?
In this article, we will learn how to do Conversion of CSV to PDF file format. This simple task can be easily done using two Steps : Firstly, We convert our CSV file to HTML using the PandasIn the Second Step, we use PDFkit Python API to convert our HTML file to the PDF file format. Approach: 1. Converting CSV file to HTML using Pandas Framework. P
3 min read
How to read CSV data into a record array in NumPy?
In NumPy, a record array (or recarray) is a specialized array that allows you to access fields as attributes, providing a convenient way to handle structured data. It is essentially a structured array that is wrapped in an object-oriented interface, making it easier to work with data that has named columns, similar to a DataFrame in pandas. Key Fea
3 min read
How to Import a CSV file into a SQLite database Table using Python?
In this article, we are going to discuss how to import a CSV file content into an SQLite database table using Python. Approach:At first, we import csv module (to work with csv file) and sqlite3 module (to populate the database table).Then we connect to our geeks database using the sqlite3.connect() method.At this point, we create a cursor object to
3 min read
PySpark - Read CSV file into DataFrame
In this article, we are going to see how to read CSV files into Dataframe. For this, we will use Pyspark and Python. Files Used: authorsbook_authorbooksRead CSV File into DataFrame Here we are going to read a single CSV into dataframe using spark.read.csv and then create dataframe with this data using .toPandas(). C/C++ Code from pyspark.sql import
2 min read
Convert Text File to CSV using Python Pandas
Let's see how to Convert Text File to CSV using Python Pandas. Python will read data from a text file and will create a dataframe with rows equal to number of lines present in the text file and columns equal to the number of fields present in a single line. See below example for better understanding. Dataframe created from upper text file will look
2 min read
Python - Convert TSV to CSV file
In this article, we will see how to Convert TSV Files to CSV using Python. Method 1: Using Regex TSV file can be converted into CSV file by reading one line of data at a time from TSV and replacing tab with comma using re library and writing into CSV file. We first open the TSV file from which we read data and then open the CSV file in which we wri
2 min read
NumPy ndarray.tolist() Method | Convert NumPy Array to List
The ndarray.tolist() method converts a NumPy array into a nested Python list. It returns the array as an a.ndim-levels deep nested list of Python scalars. Data items are converted to the nearest compatible built-in Python type. Example C/C++ Code import numpy as np gfg = np.array([1, 2, 3, 4, 5]) print(gfg.tolist()) Output[1, 2, 3, 4, 5] SyntaxSynt
1 min read
How to convert a dictionary into a NumPy array?
It's sometimes required to convert a dictionary in Python into a NumPy array and Python provides an efficient method to perform this operation. Converting a dictionary to NumPy array results in an array holding the key-value pairs in the dictionary. Python provides numpy.array() method to convert a dictionary into NumPy array but before applying th
3 min read
Convert list of Celsius values into Fahrenheit using NumPy array
Let us see how to convert a list of Celsius temperatures into Fahrenheit by converting them into NumPy array. The formula to convert Celsius to Fahrenheit is : feh = (9 * cel / 5 + 32) Method 1 : Using the numpy.array() method. C/C++ Code # importing the module import numpy as np # taking the celsius input inp = [0, 12, 45.21, 34, 99.91] # storing
2 min read
How to Convert NumPy Array of Floats into Integers
In this article, we will see how to convert the NumPy Array of Floats into Integers. We are given a NumPy array of float-type values. Our task is to convert all the float-type values of the Numpy array to their nearest array of integer values. Input1: [1.2 4.5 9.1 6.5 8.9 2.3 1.2]Output1: [1 4 9 6 8 2 1]Input2: [ 1.2 3.4 5.6 7.8 9.1 11.2 14.5 16.7]
7 min read
How to Read CSV Files with NumPy?
In this article, we will discuss how to read CSV files with Numpy in Python. Reading CSV files using Python NumPy library helps in loading large amount of data quicker. Due to performance reason, NumPy is preferred while reading huge amount of data from CSV files. Dataset in use: Read CSV Files using built-in Python open() function Here we are not
3 min read
NumPy Array Sorting | How to sort NumPy Array
Sorting an array is a very important step in data analysis as it helps in ordering data, and makes it easier to search and clean. In this tutorial, we will learn how to sort an array in NumPy. You can sort an array in NumPy: Using np.sort() functionin-line sortsorting along different axesUsing np.argsort() functionUsing np.lexsort() functionUsing s
4 min read
Python - Read CSV Column into List without header
Prerequisites: Reading and Writing data in CSV CSV files are parsed in python with the help of csv library. The csv library contains objects that are used to read, write and process data from and to CSV files. Sometimes, while working with large amounts of data, we want to omit a few rows or columns, so that minimum memory gets utilized. Let's see
2 min read
Python - Read CSV Columns Into List
CSV file stores tabular data (numbers and text) in plain text. Each line of the file is a data record. Each record consists of one or more fields, separated by commas. The use of the comma as a field separator is the source of the name for this file format. In this article, we will read data from a CSV file into a list. We will use the panda's libr
3 min read
How to Merge multiple CSV Files into a single Pandas dataframe ?
While working with CSV files during data analysis, we often have to deal with large datasets. Sometimes, it might be possible that a single CSV file doesn't consist of all the data that you need. In such cases, there's a need to merge these files into a single data frame. Luckily, the Pandas library provides us with various methods such as merge, c
3 min read
Python - Import CSV into PostgreSQL
In this article, we will see how to import CSV files into PostgreSQL using the Python package psycopg2. First, we import the psycopg2 package and establish a connection to a PostgreSQL database using the pyscopg2.connect() method. before importing a CSV file we need to create a table. In the example below, we created a table by executing the "creat
2 min read
Read a CSV into list of lists in Python
In this article, we are going to see how to read CSV files into a list of lists in Python. Method 1: Using CSV moduleWe can read the CSV files into different data structures like a list, a list of tuples, or a list of dictionaries.We can use other modules like pandas which are mostly used in ML applications and cover scenarios for importing CSV con
2 min read
Save API data into CSV format using Python
In this article, we are going to see how can we fetch data from API and make a CSV file of it, and then we can perform various stuff on it like applying machine learning model data analysis, etc. Sometimes we want to fetch data from our Database Api and train our machine learning model and it was very real-time by applying this method we can train
6 min read
Read multiple CSV files into separate DataFrames in Python
Sometimes you might need to read multiple CSV files into separate Pandas DataFrames. Importing CSV files into DataFrames helps you work on the data using Python functionalities for data analysis. In this article, we will see how to read multiple CSV files into separate DataFrames. For reading only one CSV file, we can use pd.read_csv() function of
2 min read
How to resolve a UnicodeDecodeError for a CSV file in Python?
Several errors can arise when an attempt to decode a byte string from a certain coding scheme is made. The reason is the inability of some encoding schemes to represent all code points. One of the most common errors during these conversions is UnicodeDecode Error which occurs when decoding a byte string by an incorrect coding scheme. This article w
5 min read
Scrape and Save Table Data in CSV file using Selenium in Python
Selenium WebDriver is an open-source API that allows you to interact with a browser in the same way a real user would and its scripts are written in various languages i.e. Python, Java, C#, etc. Here we will be working with python to scrape data from tables on the web and store it as a CSV file. As Google Chrome is the most popular browser, to make
3 min read
Saving Text, JSON, and CSV to a File in Python
Python allows users to handle files (read, write, save and delete files and many more). Because of Python, it is very easy for us to save multiple file formats. Python has in-built functions to save multiple file formats. Opening a text file in Python Opening a file refers to getting the file ready either for reading or for writing. This can be don
5 min read
How to delete a CSV file in Python?
In this article, we are going to delete a CSV file in Python. CSV (Comma-separated values file) is the most commonly used file format to handle tabular data. The data values are separated by, (comma). The first line gives the names of the columns and after the next line the values of each column. Approach : Import module.Check the path of the file.
2 min read
How to save a Python Dictionary to a CSV File?
Prerequisites: Working with csv files in Python CSV (comma-separated values) files are one of the easiest ways to transfer data in form of string especially to any spreadsheet program like Microsoft Excel or Google spreadsheet. In this article, we will see how to save a PYthon dictionary to a CSV file. Follow the below steps for the same. Import cs
2 min read
How to read a CSV file to a Dataframe with custom delimiter in Pandas?
Python is a good language for doing data analysis because of the amazing ecosystem of data-centric python packages. pandas package is one of them and makes importing and analyzing data so much easier.Here, we will discuss how to load a csv file into a Dataframe. It is done using a pandas.read_csv() method. We have to import pandas library to use th
3 min read
How to skip rows while reading csv file using Pandas?
Python is a good language for doing data analysis because of the amazing ecosystem of data-centric python packages. Pandas package is one of them and makes importing and analyzing data so much easier. Here, we will discuss how to skip rows while reading csv file. We will use read_csv() method of Pandas library for this task. Syntax: pd.read_csv(fil
3 min read
How to export Pandas DataFrame to a CSV file?
Let us see how to export a Pandas DataFrame to a CSV file. We will be using the to_csv() function to save a DataFrame as a CSV file. DataFrame.to_csv() Syntax : to_csv(parameters) Parameters : path_or_buf : File path or object, if None is provided the result is returned as a string. sep : String of length 1. Field delimiter for the output file. na_
3 min read
Practice Tags :