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?
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.
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.
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.
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.
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)
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")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With