Search code examples
pythonnumpycsvexport-to-csvnumpy-ndarray

My Numpy Array won't format correctly when converting to CSV file


I'm trying to convert a numpy array of dimensions (22227,2) into a csv file with 2 columns and 22227 rows. However, whenever I try to do this with the following code I get one row with twice the amount of columns.

# using open function
sample_data = np.genfromtxt("wg1_regular_baseline_trial6.csv",delimiter=",", dtype=float)
    
sample_data = np.array(sample_data)
s_data=sample_data[1000:-4000]

#find mean of original data
adjusted_value=[]
mean_wave=sample_data[:,1].mean()

#adjust data for mean value
for i in range(len(sample_data)):
    value=sample_data[i]
    adjusted_value+=[[value[0],value[1]-mean_wave]]

#create array
adjusted_data = np.array(adjusted_value)
a_data=adjusted_data[1000:-4000]
print(np.shape(adjusted_data))

#create csv file
adjusted_data.tofile('BL_Trial6.csv', sep = ',')

and the code output when I print the array for the adjusted data is

[[0.00000000e+00 2.63267449e-02]
 [1.00000000e-02 2.64037449e-02]
 [2.00000000e-02 2.62877449e-02]
 ...
 [2.22240000e+02 9.33474486e-03]
 [2.22250000e+02 1.04347449e-02]
 [2.22260000e+02 1.15347449e-02]]

I tried to use the numpy reshape tool with no success as it still printed one row with many, many columns.


Solution

  • For a simple (2,2) array:

    In [251]: arr
    Out[251]: 
    array([[  1,   2],
           [  3, -40]])
    

    compare tofile:

    In [252]: arr.tofile('test',sep=',')
    
    In [253]: more test
    1,2,3,-40
    

    with savetxt:

    In [254]: np.savetxt('test',arr, delimiter=',', fmt='%d')
    
    In [255]: more test
    1,2
    3,-40