0

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.

1
  • 1
    tofile is a simple file writer, writing just the values. It does not preserve the 2d shape. I suppose that's implied in the docs, rather than explicit. np.savetxt is better for writing a csv. But spend time to READ THE DOCS. Commented Dec 20, 2022 at 3:11

1 Answer 1

2

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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.