NumPy: Convert a NumPy array into a csv file
Convert NumPy Array to CSV File
Write a NumPy program to convert a NumPy array into a CSV file.
Sample Solution:
Python Code:
# Importing the NumPy library
import numpy
# Creating a 2D NumPy array 'data' containing nested lists of integers
data = numpy.asarray([[10, 20, 30], [40, 50, 60], [70, 80, 90]])
# Using numpy.savetxt() to save the array 'data' into a CSV file named "test.csv"
# The 'delimiter=","' argument specifies the delimiter to use in the CSV file as a comma ","
numpy.savetxt("test.csv", data, delimiter=",")
Explanation:
In the above code – data = numpy.asarray([ [10,20,30], [40,50,60], [70,80,90] ]): This line converts a list of lists into a NumPy array called 'data' with shape (3,3).
numpy.savetxt("test.csv", data, delimiter=","): Save the 'data' NumPy array as a CSV file named "test.csv" using a comma as the delimiter between values. The file will be created in the current working directory. If the file already exists, it will be overwritten.
Python-Numpy Code Editor:
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics