4

I want to write days to csv file using pandas. I used below method

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

This writes to the csv with dates in new rows. Something like below...

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

I want all the dates to be in one row and it should start by leaving the first column because I want my csv to look something like below...

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

I am new to pandas so I am not getting the idea to deal with it.

5
  • You want to transpose the dataframe? There isn't much for us to go on here, where has Heena, megha etc. appeared from? Commented Aug 17, 2018 at 10:45
  • In any file system, you cannot directly "prepend" to a file. If you one to add line to the beginning of the file, by Pandas or not, you need to read in the whole file, write the first line, then write the whole file back down. Commented Aug 17, 2018 at 10:49
  • @raganjosh, I was not aware of transpose. Just looked into it and I guess I can try transpose. Commented Aug 17, 2018 at 10:50
  • @THN, I admit. I have to write back to the file after reading it. Commented Aug 17, 2018 at 10:51
  • 2
    Yes, that and transpose will solve it for you. If the processing is complicated, you may want to do all in pandas, then write the final df down. Commented Aug 17, 2018 at 10:54

1 Answer 1

3

Try to transpose the dataframe 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)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.