Colab: 3 Ways To Save Pandas Dataframe Data

Table of Contents

Table of Contents


This post will demo 3 Ways to save pandas data.

  • download as a csv file.
  • save as a csv file to Google drive.
  • save as a Google spreadsheet to Google drive.

Download As a CSV File

Use to_csv method of DataFrame to transfer DataFrame to CSV file.
And use files.download method to download the file programatically.

from google.colab import files

df.to_csv('output.csv', encoding = 'utf-8-sig') 
files.download('output.csv')

Save As a CSV file To Google Drive

First, it needs to import drive and execute mount method.
Here will mount my google drive in this path /content/drive.
Second, use open to open a file which will be a parameter of to_csv method.

from google.colab import drive

drive.mount('/content/drive')
path = '/content/drive/My Drive/outpur.csv'

with open(path, 'w', encoding = 'utf-8-sig') as f:
  df.to_csv(f)

Save As a Google Spreadsheet To Google Drive

Here will use gspread library to help me to deal with google spreadsheet.
So, it needs to import gspread and do the Authorization.
And then, I need a spreadsheet for saving data, so I prepared a spreadsheet and get it's key(or id).
In the following code, I just save all data into spreadsheet begin at sheet1!A1 cell.

!pip install gspread

from google.colab import auth
from oauth2client.client import GoogleCredentials
import gspread
import pandas as pd

# Auth
auth.authenticate_user()
gc = gspread.authorize(GoogleCredentials.get_application_default())

spreadsheet_key = 'my_spreadsheet_key'
workbook = gc.open_by_key(spreadsheet_key)

workbook.values_update(
  'sheet!A1',
  params={
      'valueInputOption': 'USER_ENTERED'
  },
  body={
      'values': [df.columns.values.tolist()] + df.values.tolist()
  }
)

That's all.
I hope it will help you.