Tutorial Example

An Introduction to Save NumPy Array to CSV File with Python – NumPy Tutorial

Saving a numpy array to csv file can help us to share data for others or other python applications. In this tutorial, we will talk about some tips on how to save.

Check your numpy array

We often use numpy.savetxt() function to save numpy 1-D or 2-D array into text file, for example csv file. You should make your numpy array is 1-D or 2D firstly.

To understand numpy.savetxt() function, you can read this tutorial.

Understand numpy.savetxt() for Beginner with Examples – NumPy Tutorial

Save numpy array data into csv file

Here is an example to show how to do.

Create a 2-D numpy array

import numpy as np

data = np.array([[10, 20, 30], [40, 50, 60]])
print(data)

Save numpy array into csv file by formatted

In this code example, we will save numy array data into a data.csv file.

fname= 'data.csv'
np.savetxt(fname, data, fmt = '%.4f')

The data in data.csv file is:

10.0000 20.0000 30.0000
40.0000 50.0000 60.0000

From the result, we can find data in data.csv file is formatted by %.4f.