Maroof G Maroof G - 3 months ago 8
Python Question

How to create a csv file of data created in python

I am new to programming. I was wondering if anyone can help me create a csv file for the data that I created in python.
My data looks like this

import numpy as np
print np.__version__



a = 0.75 + (1.25 - 0.75)*np.random.sample(10000)
print a
b = 8 + (12 - 8)*np.random.sample(10000)
print b
c = -12 + 2*np.random.sample(10000)
print c
x0 = (-b - np.sqrt(b**2 - (4*a*c)))/(2*a)
print x0


The csv file format I am looking to create is 1 column each for a,b,c and x0 (see example below)

enter image description here

Your expert assistance will be highly appreciated

Thanks in advance :-)

Edit 1>>
Input code:

import numpy as np
print np.__version__
import csv




a = 0.75 + (1.25 - 0.75)*np.random.sample(10000)
##print a
b = 8 + (12 - 8)*np.random.sample(10000)
##print b
c = -12 + 2*np.random.sample(10000)
##print c
x0 = (-b - np.sqrt(b**2 - (4*a*c)))/(2*a)
##print x0


with open("file.csv",'w') as f:
f.write('a,b,c,x0\n')
for val in a,b,c,x0:
print val
f.write(','.join(map(str,[a,b,c,x0]))+ '\n')


Output
enter image description here

I am being able to generate the data using for loop command (see pic below). The csv format is not outputting as expected.

enter image description here

Answer

There are four range of values you need to iterate over. Every iteration should correspond to each new line written.

Try this:

import numpy as np
print np.__version__
import csv


a_range = 0.75 + (1.25 - 0.75)*np.random.sample(10000)
b_range = 8 + (12 - 8)*np.random.sample(10000)
c_range = -12 + 2*np.random.sample(10000)
x0_range = (-b_range - np.sqrt(b_range**2 - (4*a_range*c_range)))/(2*a_range)


with open("file.csv",'w') as f:
    f.write('a,b,c,x0\n')
    for a,b,c,x0 in zip(a_range, b_range, c_range, x0_range):
        f.write(','.join(map(str,[a,b,c,x0]))+ '\n')
Comments