![](/img/trans.png)
[英]How to sort data alphabetically in a csv file created in python?
[英]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 >>输入代码:
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')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.