Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Numpy exercise
  • pandas
  • Matplotlib
  • Data visulisation
  • EDA
  • Machin Learning
  • Deep Learning
  • NLP
  • Data science
  • ML Tutorial
  • Computer Vision
  • ML project
Open In App
Next Article:
Convert a NumPy array into a CSV file
Next article icon

Convert a NumPy array into a CSV file

Last Updated : 02 Feb, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

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.


Next Article
Convert a NumPy array into a CSV file

K

KaranGupta5
Improve
Article Tags :
  • Python
  • Python-numpy
  • Python numpy-io
Practice Tags :
  • python

Similar Reads

    How to convert a dictionary into a NumPy array?
    In this article, we will learn how to convert a Python Dictionary into a numpy array which is more efficient for numerical operations and provides powerful tools for matrix and array manipulationsKey Steps to Convert a Dictionary to a NumPy ArrayUse dict.items(): This returns key-value pairs from th
    3 min read
    Convert a NumPy array to an image
    Converting a NumPy array to an image is a simple way to turn numbers into pictures. A NumPy array holds pixel values, which are just numbers that represent colors. Images, like PNG or JPEG, store these pixel values in a format we can see. In this process, the NumPy array turns into an image, with ea
    3 min read
    Convert 2D float array to 2D int array in NumPy
    Converting a 2D float array to a 2D integer array in NumPy is a straightforward process using the astype() method. This conversion can be useful in various data analysis and scientific computing tasks where integer data types are required or where memory efficiency is essential. In this article, we
    8 min read
    How to convert NumPy array to list ?
    This article will guide you through the process of convert a NumPy array to a list in Python, employing various methods and providing detailed examples for better understanding. Convert NumPy Array to List There are various ways to convert NumPy Array to List here we are discussing some generally us
    4 min read
    How to convert a list and tuple into NumPy arrays?
    In this article, let's discuss how to convert a list and tuple into arrays using NumPy. NumPy provides various methods to do the same using Python. Example: Input: [3, 4, 5, 6]Output: [3 4 5 6]Explanation: Python list is converted into NumPy ArrayInput: ([8, 4, 6], [1, 2, 3])Output: [[8 4 6] [1 2 3]
    2 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences