pythonpandascsvdataframe

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?


Solution

  • 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)