将pandas数据帧转换为csv

时间:2016-10-14 11:12:29

标签: python csv pandas

enter image description here 我有上面的数据框,我希望将其转换为csv文件 我目前正在使用df.to_csv('my_file.csv')转换它,但我想留下3个空白列。对于上面文件的行,我有以下过程。

dirname = os.path.dirname(os.path.abspath(__file__))
csvfilename = os.path.join(dirname, 'MainFile.csv')
with open(csvfilename, 'wb') as output_file:
    writer = csv.writer(output_file, delimiter=',')
    writer.writerow([])
    writer.writerow(["","Amazon","Weekday","Weekend"])
    writer.writerow(["","Ebay",wdvad,wevad])
    writer.writerow(["","Kindle",wdmpv,wempv])
    writer.writerow([])

我希望在空白空间后面的数据框中加入三个空白列。如何将数据帧继续添加到现有的csv文件中,以便我还可以在数据帧之后添加包含数据的更多行。

1 个答案:

答案 0 :(得分:1)

考虑最初将数据帧输出到临时文件。然后,在创建 MainCSV 期间,读入临时文件,迭代地写入行,然后销毁临时文件。此外,在将数据帧写入csv之前,请创建三个空白列。

下面假设您需要两个任务:1)三个空白列和2)在Amazon / Ebay / Kindle行标题下面写入数据帧值。示例数据使用随机正常值和 wdvad 的标量值, wevad wdmpv wempv 是字符串文字他们的名字:

import csv, os
import pandas as pd

# TEMP DF CSV
dirname = os.path.dirname(os.path.abspath(__file__))    
df = pd.DataFrame([np.random.normal(loc=3.0, scale=1.0, size=24)*1000 for i in range(7)],
                  index=['Monday', 'Tuesday', 'Wednesday', 'Thursday', 
                         'Friday', 'Saturday', 'Sunday'])
df['Blank1'], df['Blank2'], df['Blank3'] = None, None, None   

df.to_csv(os.path.join(dirname, 'temp.csv'))       # OUTPUT TEMP DF CSV

# MAIN CSV
csvfilename = os.path.join(dirname, 'MainFile.csv')
tempfile = os.path.join(dirname, 'temp.csv')

wdvad = 'wdvad'; wevad = 'wevad'; wdmpv = 'wdmpv'; wempv = 'wempv'

with open(csvfilename, 'w', newline='') as output_file:
    writer = csv.writer(output_file)
    writer.writerow([""])
    writer.writerow(["","Amazon","Weekday","Weekend"])
    writer.writerow(["","Ebay",wdvad,wevad])
    writer.writerow(["","Kindle",wdmpv,wempv])
    writer.writerow([""])

    with open(tempfile, 'r') as data_file:
        for line in data_file:
            line = line.replace('\n', '')
            row = line.split(",")            
            writer.writerow(row)

os.remove(tempfile)                               # DESTROY TEMP DF CSV

<强>输出

CSV File Output