In today’s tutorial we’ll show you two ways to export and save a Numpy array to a text or csv file which you can then further process:
- Using the Numpy function np.savetxt
- Using the Pandas library
Create example data
We’ll start by creating a simple array:
import numpy as np import pandas as pd my_array = np.arange(10,19).reshape(3,3)
Note: Numpy and Pandas are installed by default with Anaconda distributions. In case you are using a different distribution or a virtual environment you have manually built, you might need to import both libraries into your development environment namespace. Here’s how to troubleshoot Pandas or Numpy install issues.
Save the array to a file using Numpy.savetxt
We’ll first create a new file (could by csv, txt, json or others). Then we’ll loop through the array rows and write them into the file.
# open file with write access and write the array contents with open('my_array.csv', 'w') as my_file: for i in my_array: np.savetxt(my_file,i) print('Array exported to file')
Read the array from the file with Numpy
We can easily go the opposite way and import the file contents into a Numpy array with the loadtxt ndArray method.
my_array_2 = np.loadtxt('my_array.csv') my_array_2.reshape(3,3)
Write array contents with Pandas
We can use the very powerful Pandas library to export our array matrix to a file and read it back:
import pandas as pd my_df = pd.DataFrame(my_array) my_df.to_csv('my_array.csv',header = False, index= False)
Here are the contents of our comma separated value file:
We can obviously read the file back to Pandas by using:
my_df = pd.read_csv('my_array.csv',header = None)