Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 481
THN Avatar asked May 16 '19 10:05

THN


People also ask

How do I add a header to a CSV file in Python?

The contents of the data frame are again stored back into the CSV file. In this article, we are going to add a header to a CSV file in Python. Method #1: Using header argument in to_csv() method. Initially, create a header in the form of a list, and then add that header to the CSV file using to_csv() method.

How do I assign headers to pandas DataFrame?

You can add header to pandas dataframe using the df. colums = ['Column_Name1', 'column_Name_2'] method. You can use the below code snippet to set column headers to the dataframe.

How do I write pandas DataFrame to CSV?

By using pandas. DataFrame. to_csv() method you can write/save/export a pandas DataFrame to CSV File. By default to_csv() method export DataFrame to a CSV file with comma delimiter and row index as the first column.

How do I convert a DataFrame data to a CSV file in Python?

Exporting the DataFrame into a CSV file Pandas DataFrame to_csv() function exports the DataFrame to CSV format. If a file argument is provided, the output will be the CSV file. Otherwise, the return value is a CSV format like string. sep: Specify a custom delimiter for the CSV output, the default is a comma.


2 Answers

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)
like image 188
Divyanshu Srivastava Avatar answered Sep 28 '22 00:09

Divyanshu Srivastava


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")
like image 35
Zionsof Avatar answered Sep 28 '22 02:09

Zionsof