简体   繁体   中英

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)

在此处输入图片说明

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 在此处输入图片说明

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

在此处输入图片说明

with open("file.csv",'w') as f:
  f.write('a,b,c,x0\n')
  --forloop where you generate a,b,c,x0:
    f.write(','.join(map(str,[a,b,c,x0])) + '\n')

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')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM