+3 votes
in Programming Languages by (73.8k points)
I created sample data for my ML code, which is in 2D NumPy array format. I want to save the data into a CSV file so that I can use it later. How can I save the NumPy array data as CSV file?

1 Answer

+1 vote
by (349k points)
selected by
 
Best answer

You can use savetxt() function of Numpy to save the Numpy array as a CSV file.

Here is an example:

>>> import numpy as np
>>> X
array([[-2.55680932, -0.29639853],
       [-4.63893653, -0.85596495],
       [-3.94689236,  1.44952573],
       [ 3.07662588,  0.7127008 ],
       [ 2.03985374, -1.22554641],
       [ 6.02615859,  0.21568336]])
>>> np.savetxt('opfile.csv', X, delimiter=",")

The above code will create the output file 'opfile.csv' with the following content.

Output CSV file


...