如何将dtype:float64数组写入csv-fi

2024-04-18 12:11:49 发布

您现在位置:Python中文网/ 问答频道 /正文

我是斯塔克斯洛夫的新手,但我真的希望有人能帮上忙!

我已经将一个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它只有“Number”数据,我从原始csv文件中提取数据,并复制到新的csv文件中。

print "London", London的输出,显示格式和dtype:float64


Tags: 文件csvthe数据infordatamath
1条回答
网友
1楼 · 发布于 2024-04-18 12:11:49

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

如果您想要一个三列的CSV,其中每一行都有NumberLondon和{}值,那么通过迭代锁步中的三个序列,方法是使用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])

不过,你用的是熊猫,熊猫的全部目的是避免担心这种东西。您已经在使用它来读取CSV并使用read_csv将其转换成一个漂亮的DataFrame,其中有一个简单的单行线。如果您构建了一个很好的DataFrame,并以您想要的格式输出,那么同样可以使用Pandas使用^{}通过一个简单的单行线将其写入CSV。在

这可以简单到:

^{pr2}$

相关问题 更多 >