1

In my situation, I export a data frame to a .csv file via a for loop. The dataframe for each iteration is being created from a list of dict. The exported information is correct but of course, for every iteration, headers are displayed in the csv file.

Here is the code snippet:

f = open("Test" + ".csv", "w+")
for junc in Junctions:
        conn = model.connections(Junction = junc)  #list(dict)
        DF4dictConn = pd.DataFrame(conn)           #convert to DF
        DF4dictConn['Junction'] = junc  # Add a new column
        DF4dictConn.set_index('Junction',inplace=True)  #set the new column as index
        DF4dictConn.to_csv(f,sep=',')  #export dataframe for each junction

The output of the .csv file is shown below:

enter image description here

Is there a way to avoid the repetition of the headers but only display the header once?

Conn:

enter image description here

CodeMaster
  • 431
  • 4
  • 14
  • Actually it seems a bit odd, that you write the `.csv` each iteration. Wouldn't it be better to build a proper DataFrame first and then write the ``.csv` file once? – AnsFourtyTwo Nov 19 '19 at 14:23
  • Yes, @SimonFink I did that first but I had issues in building an entire list(dict) and eventually converting it to a dataframe in one go. Is there a better way to write this code? – CodeMaster Nov 19 '19 at 14:31
  • Checkout `DataFrame.append()` function. So you can iterate over your Junctions and build one single DataFrame. – AnsFourtyTwo Nov 19 '19 at 14:33
  • updated with an image. – CodeMaster Nov 19 '19 at 14:41

1 Answers1

3

As described in the documentation of DataFrame.to_csv() you need to set the header flag. So instead, try:

DF4dictConn.to_csv(f,sep=',', header=False)  #export dataframe for each junction

If you want to display the header in the first iteration of the loop, please refer to this nice article about how to implement the Head-Tail design pattern.

AnsFourtyTwo
  • 2,480
  • 2
  • 13
  • 33