我是stackoverflow的新手,但我真的希望有人能够提供帮助!
我已经将数字的csv文件读入python,然后对它们进行了一系列计算,现在想将新数据输出到新的csv文件中。但是我想我可能对输出是什么感到困惑,所以没有调用正确的格式来保存数据。如果有人有任何帮助/建议,我将不胜感激。以下是我所做的概述...
我从original csv file中读取了数据
我正在使用的代码:
import math
import pandas as pd
import csv
# Read the file in csv
DATA = pd.read_csv("for_sof.csv")
# Extract the columns of bin counts from the csv
Bin0 = DATA.iloc[:,2]
Bin1 = DATA.iloc[:,3]
Bin2 = DATA.iloc[:,4]
Bin3 = DATA.iloc[:,5]
# calculations on the data from the original csv
Values_A = (((math.pi * Bin0) / 6 ) / 100 ) * 1.05
Values_B = (((math.pi * Bin1) / 6 ) / 100 ) * 1.05
Values_C = (((math.pi * Bin2) / 6 ) / 100 ) * 1.05
Values_D = (((math.pi * Bin2) / 6 ) / 100 ) * 1.05
# the data I want in the new csv file
London = Values_A + Values_B
Manchester = Values_C + Values_D
Number = DATA.iloc[:,0]
# writing the data to file
csvfile = "output_file.csv"
with open(csvfile, 'w') as output:
writer = csv.writer(output, lineterminator='\n')
for val in Number:
writer.writerow([val])
for val in London:
writer.writerow([val])
for val in Manchester:
writer.writerow([val])
# checking the data type
print "London", London
print "Manchester", Manchester
The ouput_file仅包含“数字”数据,我从原始csv文件中提取了该数据并将其复制到新文件中。
print "London", London的输出,显示格式和dtype:float64
答案 0 :(得分:0)
您正在编写具有所有Number
值,然后是所有London
值,然后是所有Manchester
值的单列CSV。
如果您希望使用三列CSV,其中每行具有Number
,London
和Manchester
值,则可以通过逐步锁定三个序列来实现,与zip
一起使用:
with open(csvfile, 'w') as output:
writer = csv.writer(output, lineterminator='\n')
for number, london, manchester in zip(Number, London, Manchester):
writer.writerow([number, london, manchester])
但是,您使用的是Pandas,而Pandas的全部目的是避免担心这种东西。您已经在使用它来读取CSV,并使用DataFrame
用一个简单的单行代码将它变成一个不错的read_csv
。如果您以所需的格式以所需的格式构建不错的DataFrame
,则可以使用to_csv
同样地使用Pandas将其写成带有简单衬里的CSV。
这可能很简单:
outdf = pd.DataFrame()
outdf['Number'] = DATA.iloc[:,0]
outdf['London'] = Values_A + Values_B
outdf['Manchester'] = Values_C + Values_D
outdf.to_csv(csvfile, index=False)