Converting pandas dataframe to csv

enter image description here I have the dataframe above and I wish to convert it into a csv file.
I am currently using df.to_csv('my_file.csv') to convert it but I want to leave 3 blanks columns. For the rows of the file above I have the following procedure.

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([])

I want to incorporate the data frame right after the blanks space with three blank columns. How can I add the dataframe in continuation to the existing csv file so that I can also add more rows with data after the dataframe.

Upvotes: 2

Views: 1467

Answers (1)

Parfait
Parfait

Reputation: 107747

Consider outputting data frame initially as is to a temp file. Then, during creation of the MainCSV, read in temp file, iteratively writing lines, then destroy temp file. Also, prior to writing dataframe to csv, create the three blank columns.

Below assumes you want two tasks: 1) three blank columns and 2) writing dataframe values below Amazon/Ebay/Kindle row headers. Example data uses random normal values and scalar values for wdvad, wevad, wdmpv, wempv are the string literals of their names:

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

Output

CSV File Output

Upvotes: 1

Related Questions