1) Connecting to Google Sheets¶
In [36]:
import json
import gspread
from oauth2client.service_account import ServiceAccountCredentials
Replace the following dictionary with your own Google credentials.
Follow instructions at Twilio's blog post for further details about how to get your own credentials JSON file.
Once you have the JSON file, replace the values below with your own data. 👇
In [37]:
credentials_json = {
'type': '...',
'project_id': '...',
'private_key_id': '...',
'private_key': ...',
'client_email': '...',
'client_id': '...',
'auth_uri': '...',
'token_uri': '...',
'auth_provider_x509_cert_url': '...',
'client_x509_cert_url': '...'
}
In [43]:
scope = [
'https://spreadsheets.google.com/feeds',
'https://www.googleapis.com/auth/drive'
]
credentials = ServiceAccountCredentials.from_json_keyfile_dict(credentials_json, scope)
gc = gspread.authorize(credentials)
sheet = gc.open("Legislators 2017").get_worksheet(0)
In [45]:
sheet.spreadsheet.title
Out[45]:
2) Reading rows and columns¶
In [46]:
sheet.get_all_records()[:2]
Out[46]:
In [47]:
sheet.cell(2, 1).value
Out[47]:
In [48]:
sheet.acell('B2').value
Out[48]:
In [49]:
sheet.row_values(2)
Out[49]:
In [50]:
sheet.col_values(2)[:10]
Out[50]:
In [70]:
sheet.row_count
Out[70]:
In [55]:
cell = sheet.find("Sheldon")
cell.row, cell.col
Out[55]:
3) Doing some plots¶
In [56]:
import pandas
party = sheet.col_values(8)[1:] # skip header
df = pandas.DataFrame(party)
In [69]:
df.groupby(0).size().plot.pie(figsize=(8, 8))
Out[69]:
4) Editing, inserting, deleting rows¶
In [85]:
sheet.insert_row(['This', 'is', 'a', 'new', 'row'], index=544)
Out[85]:
In [86]:
sheet.row_values(544)
Out[86]:
In [87]:
sheet.update_cell(544, 4, 'simple')
Out[87]:
In [88]:
sheet.row_values(544)
Out[88]:
In [89]:
sheet.update_acell('D544', 'simple')
Out[89]:
In [90]:
sheet.delete_row(544)
Out[90]:
In [91]:
sheet.row_values(544)
Out[91]: