THN
THN

Reputation: 3611

How to write a pandas.DataFrame to csv file with custom header?

I have a dataframe

import pandas as pd
df = pd.DataFrame([[1, 2], [3, 4]], columns=['a', 'b'])

I want to write df to a csv file but not using the columns ['a', 'b']. The first line is my custom string and the rest are the content of df.values. For example:

numrows numcols note
1 2
3 4

Can I do this with pandas or I have to manually loop through the content and write to file?

Upvotes: 13

Views: 20588

Answers (3)

Divyanshu Srivastava
Divyanshu Srivastava

Reputation: 1507

EDIT (13-08-24)

open the file with 'w' flag (as highlighted by @eric-duminil and @alessandro in the comment)

Correct code

with open('file.csv', 'w') as file:
    file.write('numrows numcols note\n')
    df.to_csv(file, header=False, index=False)

OLD

You can first create a csv file with the custom text in the first line, and then append the dataframe to it.

with open('file.csv', 'a') as file:
    file.write('Custom String\n')
    df.to_csv(file, header=False, index=False)

Also, see this post.

So, in your case, just use this

with open('file.csv', 'a') as file:
    file.write('numrows numcols note\n')
    df.to_csv(file, header=False, index=False)

Upvotes: 13

Zionsof
Zionsof

Reputation: 1246

Improving over @Divyanshu Srivastava answer:

Not that it matters a lot, but no need for keeping open files:

with open(file_path, 'w') as f:
     f.write('Custom String\n')

df.to_csv(file_path, header=False, mode="a")

Upvotes: 10

jezrael
jezrael

Reputation: 862661

First write custom string and then all data without columns in append mode:

file = 'file.csv'
pd.DataFrame(columns=['numrows numcols note']).to_csv(file, index=False)
df.to_csv(file, header=None, index=False, mode='a')

Upvotes: 2

Related Questions