簡體   English   中英

如何將dtype數組:float64寫入csv文件

[英]How to write array of dtype: float64 into a csv file

我是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

ouput_file僅包含“ Number”數據,我從原始csv文件中提取了該數據並將其復制到新文件中。

打印“倫敦”(倫敦)的輸出顯示格式和dtype:float64

您正在編寫一個單列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並將其轉換為使用read_csv的簡單DataFrame的漂亮read_csv 如果您以所需的格式以所需的輸出構建一個不錯的DataFrame ,則可以使用to_csv同樣使用Pandas將其寫成具有簡單to_csv的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)

無法從 dtype('

[英]Cannot cast array data from dtype('<M8[ns]') to dtype('float64') according to the rule 'safe'

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM