Last active
February 1, 2018 06:41
-
-
Save rmharrison/6885b4972836f34648a4ae3cbd1440a5 to your computer and use it in GitHub Desktop.
GOT API with Pandas
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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