mad
mad

Reputation: 2789

Numpy is not saving csv properly

I have a simple numpy array made of floats and integers

array_to_save=np.array([shutter_time,int(nb_frames),np.mean(intensities),np.std(intensities)])

I would like to save this numpy array, appending it to an existing csv file by doing the following.

    with open('frames_stats.csv','a') as csvfile:
     
        np.savetxt(csvfile,array_to_save,delimiter=',')

However, it saves this array not as an ordinary csv file, where there were supposed to be 4 values separated by commas, but it saves each value as a new line of the file such as follows:

5.000000000000000000e-01 1.495000000000000000e+03 2.340000000000000000e+02 0.000000000000000000e+00 5.000000000000000000e-01 1.495000000000000000e+03 2.340000000000000000e+02 0.000000000000000000e+00

How can I save such a csv file properly?

Upvotes: 1

Views: 91

Answers (3)

Serge Ballesta
Serge Ballesta

Reputation: 149085

You could simply reshape your array to change you 1D array of dimension 4 to a 2D array of dimensions (1, 4):

with open('frames_stats.csv','a') as csvfile:
    np.savetxt(csvfile,array_to_save.reshape((1, 4)),delimiter=',')

Upvotes: 1

wrbp
wrbp

Reputation: 890

You are saving a one dimension array (1 column) but you are expecting the result of a 2 dimensions array with one line, so in order to have the desired result do this

array_to_save=np.array([[shutter_time,int(nb_frames),np.mean(intensities),np.std(intensities)]])

see the double square brackets

Upvotes: 1

Related Questions