Skip to content Skip to sidebar Skip to footer

How To Save Feature Matrix As Csv File

I have several features of Image and after image pre-processing I have plenty of data which I need to use frequently in future works. So to save time I want to save the data of ima

Solution 1:

You can use structured array if you want to include attribute name to numpy array. But that will make things a bit more complicated to use. I would rather save the numpy array with same types and save the attributes name somewhere else. That is more straight forward and easier to use.

Example: For the sake of simplicity, let's say that you have three col arrays of length 4: a, b, c

a -> array([[1],
           [2],
           [3],
           [4]])

a.shape -> (4,1)

b and c array have same array shape.

For the sake of faster access to the data, it would be better to make that as a row array so that it is stored continuously on the disk and memory when loaded.

a = a.ravel(); b = b.ravel(); c = c.ravel()
a - > array([1, 2, 3, 4])
a.shape -> (4,)

Then, you stack them into a large array and save it to csv file.

x = np.vstack((a,b,c))
array([[1, 2, 3, 4],
       [5, 6, 7, 8],
       [9, 10, 11, 12]])
x.shape -> (3,4)

Then, just save this stacked array to csv file.

np.savetxt('out.csv', x, delimiter=',')

This can be done in one line:

np.savetxt('out.csv', np.vstack(a.ravel(), b.ravel(), c.ravel()), delimiter='x')

Solution 2:

For example if yo got your out put into a variable "result" then you can save that result in csv format using the below commands

import pandas as pd
result = "......................"(your expression)
result1 = pd.DataFrame({'col1':result[:,0],'col2':result[:,1]})
result1.to_csv('Myresult.csv', header = False)

in the place of "Myresult" you can mention your desire path of output. In my case it would be like "C:\Users\dinesh.n\Desktop\Myresult.csv". I hope it clears your doubt if not please excuse me and correct me. Thank you.


Post a Comment for "How To Save Feature Matrix As Csv File"