Federico Gentile Federico Gentile - 1 year ago 103
Python Question

Saving dataframe and additional data in same .csv file with Pandas

Description: I have a set of parameters (

) and a dataframe
. In this example the parameters and the number of columns of the dataframe are respectively are 4 and 3 but they could both be a generic number.

import pandas as pd
import numpy as np

# list of parameters
par1 = 1.05
par2 = 20
par3 = 50000
par4 = 12315468

# Dataframe
dic = {'A' : ['PINCO','PALLO','TOLLO','FINGO','VOLVA'],
'B' : [ 4 , 5 , np.nan, 1 , 0],
'C' : [ 1 , 4 , 8 , 7 , 6]}
df = pd.DataFrame(dic)

My goal is to save this data in the same .csv file but I don't know how to do it since the number of parameters doesn't match the number of columns of

My output file must should follow this rule:

  • first row: list of parameters

  • second row and after: content of dataframe

Therefore it looks like this:

enter image description here

Question: Could you provide a smart and efficient way to obtain the output file with the desired shape?

Answer Source

First create list of parameters par1, par2, par3, etc,.

l = [par1, par2, par3, par4]

Then save the list to csv

filename = 'abc.csv'
pd.DataFrame(l).T.to_csv(filename, index=False, header=False)

Use python's append mode to append the data frame to csv.

with open(filename, 'a') as f:  # Use append mode.
    df.to_csv(f, index=False, header=False)