w3resource

NumPy: Convert a NumPy array into a csv file

NumPy: Array Object Exercise-102 with Solution

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:

Previous: Write a NumPy program to print the full NumPy array, without truncation.
Next: Write a NumPy program to calculate the Euclidean distance.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.