Adding a comment with "to_csv" with pandas

I am saving a DataFrame using a method to_csv

and the result looks like this:

2015 04 08 0.0 14.9
2015 04 09 0.0  9.8
2015 04 10 0.3 23.0

      

but I need to make some changes to this output, I need to add a comment and a column with constant value and the same size as the rest of the columns. I need to get an output like this:

#Data from the ...
#yyyy mm dd pcp temp er
2015 04 08 0.0 14.9 0
2015 04 09 0.0  9.8 0
2015 04 10 0.3 23.0 0

      

Does anyone know how to do this?

+3


source to share


2 answers


Column names should be saved automatically, if it really is a framework pandas

check it out by typing:

print df.columns 

      



where df

is your namepd.DataFrame()

0


source


The easiest way is to add a comment first and then add a data frame. There are two approaches to doing this below, and there is more information at Writing comments to a CSV file with pandas .

Reading in test data

import pandas as pd
# Read in the iris data frame from the seaborn GitHub location
iris = pd.read_csv('https://raw.githubusercontent.com/mwaskom/seaborn-data/master/iris.csv')
# Create a bigger data frame
while iris.shape[0] < 100000:
    iris = iris.append(iris)
# `iris.shape` is now (153600, 5)

      

1. Add with the same file handler



# Open a file in append mode to add the comment
# Then pass the file handle to pandas
with open('test1.csv', 'a') as f:
    f.write('# This is my comment\n')
    iris.to_csv(f)

      

2. Run the file again with to_csv(mode='a')

# Open a file in write mode to add the comment
# Then close the file and reopen it with pandas in append mode
with open('test2.csv', 'w') as f:
    f.write('# This is my comment\n')
iris.to_csv('test2.csv', mode='a')

      

0


source







All Articles