如何创建 python 中创建的数据的 csv 文件

How to create a csv file of data created in python

我是编程新手。我想知道是否有人可以帮助我为我在 python 中创建的数据创建一个 csv 文件。 我的数据看起来像这样

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

我要创建的 csv 文件格式是 a、b、c 和 x0 各 1 列(参见下面的示例)

非常感谢您的专家协助

提前致谢:-)

编辑 1>> 输入代码:

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

输出

我能够使用 for 循环命令生成数据(见下图)。 csv 格式未按预期输出。

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

您需要迭代四个值范围。每次迭代都应对应于写入的每个新行。

试试这个:

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