Skip to content

Instantly share code, notes, and snippets.

@rmharrison
Last active February 1, 2018 06:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rmharrison/6885b4972836f34648a4ae3cbd1440a5 to your computer and use it in GitHub Desktop.
Save rmharrison/6885b4972836f34648a4ae3cbd1440a5 to your computer and use it in GitHub Desktop.
GOT API with Pandas
# TinyURL to this script: https://tinyurl.com/gotpandas
# Interactive API: https://anapioficeandfire.com/
# https://raw.githubusercontent.com/joakimskoog/AnApiOfIceAndFire/master/data/characters.json
# https://tinyurl.com/gotchararacters
# Installation
# Requires: python, requests, pandas
# Optional: matplotlib
## Linux / Ubuntu
# sudo apt-get install python
# sudo apt-get install pip
## OSX
# brew install python
# Import statements
import requests # pip install requests
import pandas as pd # pip install pandas
# Get the JSON blob
response = requests.request('GET', 'https://tinyurl.com/gotchararacters')
json_blob = response.text
# Load into pandas
df = pd.read_json(json_blob)
# What data do I have?
df.columns
# Optional: Save to csv
df.to_csv('characters.csv')
## Query examples
df[df.Culture=='Reach'].Name
df.query("Culture == 'Reach'")[['Name', 'Died']]
## Groupby examples
df.groupby('IsFemale').Id.count()
df.groupby('Culture').Id.count()
df.groupby(['Culture', 'IsFemale']).Id.count()
## Optional: Plotting examples
import matplotlib.pyplot as plt # pip install matplotlib
plt.gcf() # So plotting shows by default. Alt, can use `plt.show()` every time you want to see the plot.
df.Culture.value_counts()[1:].plot()
df.IsFemale.value_counts().plot.bar()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment