python - 如何将 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
解决方案
您正在编写一个单列 CSV,其中首先包含所有Number
值,然后是所有London
值,然后是所有Manchester
值。
如果您想要一个三列 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
用你想要的格式构建一个不错的输出,你同样可以使用 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)
推荐阅读
- javascript - 如何在javascript中按空格和特殊字符分割字符串?
- linux - 在 Pycharm 中修改 Python 代码后,如何将更改部署到我的 Portainer?
- vue.js - 如何在 vuetify 数据表中添加单个列搜索(文本输入)?
- forms - 如何在表单中添加 curl `-H` 参数?
- java - MockitoJunitRunner 可以模拟 Spring @Configuration 类,但所有字段均为空
- ios - 如何从fireBase推送通知swift 4中获取数据
- spring - CXF 总是返回第一次打开它的 WSDL 中的 url
- lua - LUA 以 YYYYMMDDHHMMSS 格式获取日期时间
- javascript - 如何对第一次axios调用的数组结果进行后续的axios调用?
- mysql - Mysql 检索去年同月的订单,与今天相同