komodovaran_
komodovaran_

Reputation: 2012

Add rows *on top of* column names Pandas Dataframe as header info?

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.

Upvotes: 1

Views: 3605

Answers (1)

James
James

Reputation: 36608

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)

Upvotes: 4

Related Questions