将Python结果导出为CSV

时间:2016-07-07 18:18:58

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

请放轻松,我是学生!

我无法将以下代码的结果导出为CSV格式。对于每个循环(硬币翻转),我需要将结果导出为名为RESULTS.CSV的CSV作为新的ROW。

我已尝试在StackOverflow上发布了四种不同的方法但到目前为止都没有成功。我很难理解语法/逻辑。我讨厌问这个并且总是试图避免它,但有人会介意给我一个简单的解决方案,以便我可以剖析逻辑吗? (而不是引用一篇文章,因为我已经尝试了解它们但遇到了麻烦)

版本:Python 3.5

import random

flipcount=int(input("How many times should I flip a coin?\n###:"))

samples = [ random.randint(1, 2) for i in range(flipcount) ]
heads = samples.count(1)
tails = samples.count(2)

for s in samples:
    msg = 'Heads' if s==1 else 'Tails'
    print(msg)

print ("Heads count=%d, Tails count=%d" % (heads, tails))

这是一次失败的尝试......我相信我已经完成了对这个主题的研究,并且让自己大为困惑......

import random
import csv

flipcount=int(input("How many times should I flip a coin?\n###:"))


samples = [ random.randint(1, 2) for i in range(flipcount) ]
heads = samples.count(1)
tails = samples.count(2)
writer = csv.writer(w)

for s in samples:
    msg = 'Heads' if s==1 else 'Tails'
    print(msg)
    with open('some.csv', 'w', newline='') as f:
        writer.writerows(msg)

print ("Heads count=%d, Tails count=%d" % (heads, tails))

2 个答案:

答案 0 :(得分:1)

import pandas as pd
import numpy as np
#get the flipcount
flipcount = int(input("How many times should I flip a coin?\n###:"))
samples = np.random.randint(0, 2, size = flipcount)
#create a pandas dataframe
data = pd.DataFrame(["heads" if i == 1 else "Tails" for i in samples])
#create a csv file
data.to_csv("data.csv", index=False, header=False)

答案 1 :(得分:0)

这会奏效。现在,您可以将其附加到列表“数据”,而不仅仅是打印结果。每行数据'将包含您的一个结果。然后你写下列表'数据'到csv文件,看起来就像你要求的那样。

import csv 

data = []
for s in samples:
    msg = 'Heads' if s==1 else 'Tails'
    data.append(msg)

with open('flip_file.csv', 'wb') as f:
    writer = csv.writer(f)
    writer.writerows(data)