1

So I can export a DataFrame in a standard format, e.g.

A    B    C
val  val  val
val  val  val

But if I want the data to be reverse compatible with some older software I need to have 4 header rows, regardless of their content. It could be e.g.

nan  nan  nan
nan  nan  nan
nan  nan  nan
nan  nan  nan
A    B    C
val  val  val
val  val  val

Is there a simple internal way of accomplishing this? I guess one could export a CSV, then import it, and add the new lines, but that sounds like a hacky detour. Especially for many exported files.

komodovaran_
  • 1,940
  • 16
  • 44
  • 1
    The header row is not part of the numpy array pandas keeps for managing the values, so I don't think what you are trying to do can be done elegantly. This smells like an XY problem to me, i.e. you are asking about your attempted solution rather than the actual problem. – timgeb May 24 '18 at 15:21

1 Answers1

4

You can write out the data frame to a file object, and simply write the pre-header lines beforehand.

import pandas as pd

df = pd.DataFrame({'A':[1,2,3], 'B':[4,5,6], 'C':[7,8,9]})

with open('out.csv', 'w') as fp:
    fp.write(',,,\n'*4)
    df.to_csv(fp, index=False)
James
  • 32,991
  • 4
  • 47
  • 70