![](/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.