12

I have been stuck on how to download a pandas DataFrame into my local disk (or onto Google Drive) after creating it in Google Colab. I have tried converting it to bytes, a string (using pd.to_string), a dict (pd.to_dict), but nothing seems to work.

Additionally, I've looked at using the drive.CreateFile method as explained in the intro Colab Code and as specified here: How to download file created in Colaboratory workspace?, but I'm not sure how to apply this to pandas.

Any help is appreciated - thanks!

roganjosh
  • 10,918
  • 4
  • 25
  • 39
Brian Li
  • 123
  • 1
  • 1
  • 4

2 Answers2

29

Maybe something like this.

from google.colab import files

df.to_csv('df.csv')
files.download('df.csv')
Davide Fiocco
  • 3,631
  • 1
  • 23
  • 53
korakot
  • 24,489
  • 13
  • 84
  • 114
  • Thank you! This is perfect – Brian Li Feb 20 '18 at 03:09
  • 3
    As a side note, this might fail on some browsers (works fine on Chrome, but e.g. fails on Firefox Quantum with a `MessageError: TypeError: NetworkError when attempting to fetch resource.` in which otherwise other colab functionality works fine). – Davide Fiocco Mar 23 '18 at 10:38
1

For google colab, i recommend use Pydrive. Your answer can be found in here How to download file created in Colaboratory workspace?

edit: just change filename.csv to filename.zip or filename.blabla in lines

uploaded = drive.CreateFile({'title': 'filename.csv'})
uploaded.SetContentFile('filename.csv')

why? because this line

uploaded.SetContentFile('filename.csv')

auto set format for you content file, so you don't need to converter it to String or Byte.

Mohamed Jihad
  • 458
  • 3
  • 5