Search code examples
pythoncsvnumpyenumeratefile-writing

Wrong CSV printing in Python (enumerating numpy array)


I apologize if this question looks like a duplicate. I am trying to write a 7x2 array to a .csv file. The array I want to print is called x5:

x5
Out[47]: 
array([[  0.5,   1. ],
       [  0.7,   3. ],
       [  1.1,   5. ],
       [  1.9,   6. ],
       [  2. ,   7. ],
       [  2.2,   9. ],
       [  3.1,  10. ]])

The code I use:

import time
import csv
import numpy
timestr = time.strftime("%Y%m%d-%H%M%S")
with open('mydir\\AreaIntCurve'+'_'+str(timestr)+'.csv', 'w') as csvfile:
    writer = csv.writer(csvfile)
    writer.writerow(['Unique value', ' Occurrences'])
    for m, val in numpy.ndenumerate(x5):
        writer.writerow([m, val])

The result I get:

Unique value, Occurrences
"(0, 0)",0.5
"(0, 1)",1.0
"(1, 0)",0.69999999999999996
"(1, 1)",3.0 
"(2, 0)",1.1000000000000001
"(2, 1)",5.0
"(3, 0)",1.8999999999999999
"(3, 1)",6.0
"(4, 0)",2.0
"(4, 1)",7.0
"(5, 0)",2.2000000000000002
"(5, 1)",9.0
"(6, 0)",3.1000000000000001
"(6, 1)",10.0

The result I want:

Unique value, Occurrences
0.5, 1
0.7, 3
1.1, 5
1.9, 6
2.0, 7
2.2, 9
3.1, 10 

I assume the problem is with ndenumerate(x5), which prints the coordinates of my values. I have tried different approaches like numpy.savetxt, but it does not produce what I want and also does not print the current date in the file name. How to amend the ndenumerate() call to get rid of the value coordinates, while keeping the current date in the file name? Thanks a lot!


Solution

  • replace this line

    for m, val in numpy.ndenumerate(x5):
        writer.writerow([m, val])
    

    with:

    for val in x5:
        writer.writerow(val)
    

    you dont need to do ndenumerate