Python – Use Pandas to write a line to a csv file

Use Pandas to write a line to a csv file… here is a solution to the problem.

Use Pandas to write a line to a csv file

I want to use pandas to write days to a csv file. I used the following method

#create new df
df = pd. DataFrame({'col':day})
df.to_csv('test.csv', mode='a', index = False, header=False)

This writes the CSV with the date in a new line.
Something like the following….

01-08-2018
02-08-2018
03-08-2018
04-08-2018

I want all dates to be in one row and should start with the first column because I want my csv to look like this….

       01/08/18  02/08/18  03/08/18 ...
Heena
Megha
Mark

I’m new to Pandas, so I didn’t know what to do with it.

Solution

Try transposing the data frame before writing.

>>> df=pd. DataFrame()
>>> df['co1']=pd.date_range(start='08/01/18',periods=4)
>>> df. T
         0          1          2          3
co1 2018-08-01 2018-08-02 2018-08-03 2018-08-04

>>> df. T.to_csv('test.csv',mode='a',index=False,header=False)

Related Problems and Solutions