首页 > 解决方案 > 如何将 dtype 数组:float64 写入 csv 文件

问题描述

我是stackoverflow的新手,但我真的希望有人能提供帮助!

我已经将数字的csv文件读入python,然后用它们进行了一系列计算,现在想将新数据输出到一个新的csv文件中。但是我想我可能对输出是什么感到困惑,所以我没有调用正确的格式来保存数据。如果有人有任何帮助/建议,我将不胜感激。以下是我所做的概述......

我从中读取数据的原始 csv 文件

我正在使用的代码:

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

包含“数字”数据的输出文件,我从原始 csv 文件中提取并复制到新文件中。

print "London", London的输出显示格式和数据类型:float64

标签: pythoncsv

解决方案


您正在编写一个单列 CSV,其中首先包含所有Number值,然后是所有London值,然后是所有Manchester值。

如果您想要一个三列 CSV,其中每行都有NumberLondonManchester值,通过以锁步方式迭代三个序列,方法是使用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用你想要的格式构建一个不错的输出,你同样可以使用 Pandas 将它写入一个带有简单单行符的 CSV,使用to_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)

推荐阅读