【问题标题】:How to create a csv file of data created in python如何创建在python中创建的数据的csv文件
【发布时间】:2017-01-09 15:02:45
【问题描述】:

我是编程新手。我想知道是否有人可以帮我为我在 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 格式未按预期输出。

【问题讨论】:

    标签: python python-2.7 python-3.x csv export-to-csv


    【解决方案1】:
    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')
    

    【讨论】:

    • 正确。还要在 for 循环之前添加f.write('a,b,c,x0\n')
    • @chefarov 确实,如果他想要看起来他想要的标题。谢谢。
    • 感谢您对这个 bravosierra99 和 @chefarov 的帮助。能否举例说明如何编写 for 循环来生成数据?
    • @MaroofG 嗯,你可能想多花点时间在谷歌上搜索。大约需要 2 分钟才能弄清楚如何编写 for 循环。
    • @bravosierra99:我无法按预期在 4 个单独的列中获取数据。这是我的代码:>>> 我无法在此处以正确的格式编写代码.这对我来说是全新的,请多多包涵。
    【解决方案2】:

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

    试试这个:

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

    【讨论】:

    • 完全符合我的预期!。感谢您的帮助@chefarov :-)
    猜你喜欢
    • 2011-04-12
    • 2021-08-30
    • 2016-09-27
    • 1970-01-01
    • 1970-01-01
    • 2022-10-20
    • 2017-03-26
    • 2019-11-17
    • 2018-07-16
    相关资源
    最近更新 更多