0

I have 3 dataframes with dimensions (a*2,b*2,c*2) whereas a,b,c are different numbers. I want to add them in a single csv file but it is getting over-write every time. I used this
pandas DataFrame output end of csv

but unable to do it.

My code-

list_df = [df1, df2, df3]
for ii list_df:
   with open("cumulative_score.csv",'a',encoding='utf-8') as r:
       ii.to_csv(r)

But ,the final output ,I am getting is the last dataframe only instead of all the other dataframes.

Beginner
  • 721
  • 11
  • 27
  • you seem to have missed header=False – dartdog Sep 26 '18 at 14:50
  • I want them under same sheet – Beginner Sep 26 '18 at 14:50
  • Related, but not exactly a duplicate (since it doesn't answer why this doesn't work: it only answers how to get it working instead): https://stackoverflow.com/questions/17530542/how-to-add-pandas-data-to-an-existing-csv-file (or, indeed, your own linked question). – 9769953 Sep 26 '18 at 14:51
  • @dartdog That is intentional, my files don't have header columns otherwise ,I'll be ignoring data points only – Beginner Sep 26 '18 at 14:51
  • The lack of header may be the issue with mode='a' and header false, shouldn't be since that only affects how 1st row handled – dartdog Sep 26 '18 at 14:54
  • Can you append normally to a file? So use `r.write("something")` instead of `ii.to_csv(r)` in your code, and see if you get three lines with "something". – 9769953 Sep 26 '18 at 14:55
  • @9769953 even when I am not using a loop and writing dataframes line by line, it doesn't work – Beginner Sep 26 '18 at 14:57
  • That wasn't my question: can you append normal text to a standard (text) file? – 9769953 Sep 26 '18 at 14:58
  • @9769953 Let me check – Beginner Sep 26 '18 at 14:59
  • @dartdog it doesn't work even after header=false – Beginner Sep 26 '18 at 15:00
  • @9769953 Yes, it is appending but in same line – Beginner Sep 26 '18 at 15:04
  • 1
    The same line part is understandable: there is no newline in that string. At least it's not something in your OS / filesystem that is preventing files from being appended. It could be a bug in Pandas to_csv method then. – 9769953 Sep 26 '18 at 20:27

1 Answers1

1

The to_csv() method has a mode option; try using that instead:

list_df = [df1, df2, df3]
for df in list_df:
   df.to_csv("cumulative_score.csv", mode='a')
9769953
  • 10,344
  • 3
  • 26
  • 37