Lab 4 - Pageviews

Professor Brian Keegan
Department of Information Science, CU Boulder
This notebook is copyright and made available under the Apache License v2.0 license.

This is the third of five lab notebooks that will explore how to analyze the structure of collaborations in Wikipedia data about users' revisions across multiple articles. This lab will extend the methods in the previous two labs about analyzing a single article's revision histories and analyzing the hyperlink networks around a single Wikipedia page. You do not need to be fluent in either to complete the lab, but there are many options for extending the analyses we do here by using more advanced queries and scripting methods.

Acknowledgements
I'd like to thank the Wikimedia Foundation for the PAWS system and related Wikitech infrastructure that this workbook runs within. Yuvi Panda, Aaron Halfaker, Jonathan Morgan, and Dario Taraborelli have all provided crucial support and feedback.

Confirm that basic Python commands work

a = 3
b = 4
c = 5
(c-a)**b
16

Import modules and setup environment

Load up all the libraries we'll need to connect to the database, retreive information for analysis, and visualize results.

# Makes the plots appear within the notebook
%matplotlib inline

# Two fundamental packages for doing data manipulation
import numpy as np                   # http://www.numpy.org/
import pandas as pd                  # http://pandas.pydata.org/

# Two related packages for plotting data
import matplotlib.pyplot as plt      # http://matplotlib.org/
import seaborn as sb                 # https://stanford.edu/~mwaskom/software/seaborn/

# Package for requesting data via the web and parsing resulting JSON
import requests                      # http://docs.python-requests.org/en/master/
import json                          # https://docs.python.org/3/library/json.html
from bs4 import BeautifulSoup        # https://www.crummy.com/software/BeautifulSoup/bs4/doc/

# Two packages for accessing the MySQL server
import pymysql                       # http://pymysql.readthedocs.io/en/latest/
import os                            # https://docs.python.org/3.4/library/os.html

# Setup the code environment to use plots with a white background and DataFrames show more columns and rows
sb.set_style('whitegrid')
pd.options.display.max_columns = 100
pd.options.display.max_rows = 110

Define an article to examine pageview dynamics.

page_title = 'Star Wars'

Get pageview data for a single article

Details about the Wikimedia REST API for pageviews is available here. Unfortunately, this data end point only provides information going back to July 1, 2015.

This is what the API returns as an example.

# Get today's date and yesterday's date
today = pd.datetime.today()
yesterday = pd.datetime.today() - pd.to_timedelta('1 day')

# Date
today_date_s = str(today.date())
yesterday_date_s = str(yesterday.date())

# Convert to strings
today_s = pd.datetime.strftime(today,'%Y%m%d00')
yesterday_s = pd.datetime.strftime(yesterday,'%Y%m%d00')

# Get the pageviews for today and yesterday
url_string = 'http://wikimedia.org/api/rest_v1/metrics/pageviews/per-article/en.wikipedia/all-access/all-agents/{0}/daily/{1}/{2}'
print(url_string.format(page_title.replace(' ','_'),yesterday_s,today_s))
http://wikimedia.org/api/rest_v1/metrics/pageviews/per-article/en.wikipedia/all-access/all-agents/Star_Wars/daily/2016103100/2016110100

Write a function to get the pageviews from January 1, 2015 (in practice, the start date will be as late as August or as early as May) until yesterday.

def get_daily_pageviews(page_title,today_s):
    url_string = 'http://wikimedia.org/api/rest_v1/metrics/pageviews/per-article/en.wikipedia/all-access/all-agents/{0}/daily/2015010100/{1}'
    req = requests.get(url_string.format(page_title,today_s))

    json_s = json.loads(req.text)
    if 'items' in json_s.keys():
        _df = pd.DataFrame(json_s['items'])[['timestamp','views','article']]
        _df['timestamp'] = pd.to_datetime(_df['timestamp'],format='%Y%m%d00')
        _df['weekday'] = _df['timestamp'].apply(lambda x:x.weekday())
        return _df

Get the data for your page.

pageview_df = get_daily_pageviews(page_title,today_s)
pageview_df.head()
timestamp views article weekday
0 2015-07-01 13636 Star_Wars 2
1 2015-07-02 13901 Star_Wars 3
2 2015-07-03 14129 Star_Wars 4
3 2015-07-04 15633 Star_Wars 5
4 2015-07-05 17048 Star_Wars 6

Interpret page view results

What does the pageview activity look like? Are there any bursts of attention? What might these bursts be linked to?

ax = pageview_df.plot.line(x='timestamp',y='views',logy=False,legend=False)
ax.set_xlabel('')
ax.set_ylabel('Pageviews')
<matplotlib.text.Text at 0x7f59d6e73cc0>

Use a logarithmic scaling for the y-axis to see more of the detail in the lower-traffic days.

ax = pageview_df.plot.line(x='timestamp',y='views',logy=True,legend=False)
ax.set_xlabel('')
ax.set_ylabel('Pageviews')
<matplotlib.text.Text at 0x7f59d4bfeb00>

What are the dates for the biggest pageview outliers? Here we define an "outlier" to be more than 3 standard deviations above the average number of pageviews over the time window.

std_threshold = 4
threshold_val = pageview_df['views'].mean() + pageview_df['views'].std() * std_threshold
peak_days = pageview_df[pageview_df['views'] > threshold_val]

peak_days.head(10)
timestamp views article weekday
168 2015-12-16 352129 Star_Wars 2
169 2015-12-17 447172 Star_Wars 3
170 2015-12-18 632564 Star_Wars 4
171 2015-12-19 631137 Star_Wars 5
172 2015-12-20 563190 Star_Wars 6
173 2015-12-21 497961 Star_Wars 0
174 2015-12-22 395273 Star_Wars 1
178 2015-12-26 345159 Star_Wars 5
179 2015-12-27 344231 Star_Wars 6

How much of the total pageview activity occurred on these days compared to the rest of the pageviews?

peak_fraction = pageview_df.loc[peak_days.index,'views'].sum()/pageview_df['views'].sum()

print('{0:.1%} of all pageviews occurred on the {1} peak days.'.format(peak_fraction,len(peak_days)))
20.3% of all pageviews occurred on the 9 peak days.

How does pageview activity change over the course of a week?

g = sb.factorplot(x='weekday',y='views',data=pageview_df,kind='bar',color='grey',
                  aspect=1.67,estimator=np.median)
ax = g.axes[0][0]
ax.set_xticklabels(['Mon','Tue','Wed','Thu','Fri','Sat','Sun'],rotation=0)
ax.set_xlabel('')
ax.set_ylabel('Average pageviews')
<matplotlib.text.Text at 0x7f59d4c4fcf8>

Compare pageviews to another page

Lets write a function that takes a list of article names and returns a DataFrame indexed by date, columned by articles, and values being the number of pageviews.

def get_multiple_pageviews(page_list,today_s):
    multiple_pv_df = pd.DataFrame(index=pd.date_range('2015-05-01', today_date_s))
    for page in page_list:
        pv_df = get_daily_pageviews(page,today_s)
        try:
            multiple_pv_df[page] = pv_df.set_index('timestamp')['views'] 
        except:
            print("Error on: {0}".format(page))
            multiple_pv_df[page] = np.nan
    return multiple_pv_df.dropna(how='all')

Enter two related pages for which you want to compare their pageview behavior.

page_list = ['Star Wars','Harry Potter']

Get both of their data.

# Get the data
multiple_pvs = get_multiple_pageviews(page_list,today_s)

# Show the top rows
multiple_pvs.tail()
Star Wars Harry Potter
2016-10-27 14934.0 16511.0
2016-10-28 14747.0 17226.0
2016-10-29 18983.0 19781.0
2016-10-30 22908.0 21305.0
2016-10-31 31255.0 19684.0

Plot the data.

multiple_pvs.plot(logy=True)
<matplotlib.axes._subplots.AxesSubplot at 0x7f59d4ce52e8>

What is the correlation coefficient between these two articles' behavior?

multiple_pvs.apply(np.log).corr()
Star Wars Harry Potter
Star Wars 1.000000 0.025045
Harry Potter 0.025045 1.000000

How did the ratio between the two articles' pageviews change over time?

ratio_s = multiple_pvs[page_list[0]].div(multiple_pvs[page_list[1]])
ax = ratio_s.plot()
ax.set_ylabel('{0}/{1}'.format(page_list[0],page_list[1]))
<matplotlib.text.Text at 0x7f59d4a704a8>

Use the functions for resolving redirects and getting page outlinks from prior labs.

# From http://stackoverflow.com/a/312464/1574687
def make_chunks(l, n):
    """Yield successive n-sized chunks from l."""
    for i in range(0, len(l), n):
        yield l[i:i + n]

def resolve_redirects(page_title_list):
    # Chunk the pages into a list of lists of size 50
    chunks = make_chunks(page_title_list,50)
    # Create an empty list to fill with the redirected titles
    redirected_page_titles = []
    # For each chunk try to get the redirects
    for chunk in chunks:
        # Create the query string that separates spaces within page titles by '+' 
        # and separates page titles by '|'
        page_titles_string = '|'.join([page.replace(' ','+') for page in chunk])
        # Put this large string into the URL
        url_string = 'https://en.wikipedia.org/w/api.php?action=query&format=json&prop=pageprops&titles={0}+&redirects=1'.format(page_titles_string)
        # Do the query and parse the JSON response into a dictionary
        req = json.loads(requests.get(url_string).text)
        # Convert the returned values containing redirects into a dictionary
        if 'redirects' in req['query'].keys():
            redirected_titles = {d['from']:d['to'] for d in req['query']['redirects']}
            # Add the redirected titles to the list
            for title in chunk:
                try:
                    #print(len(redirected_page_titles), title, redirected_titles[title])
                    redirected_page_titles.append(redirected_titles[title])
                # If they don't have a redirect just add the original title
                except KeyError:
                    #print(len(redirected_page_titles), '\nFrom: ', title, '\nTo: ', title)
                    redirected_page_titles.append(title)
        else:
            for title in chunk:
                redirected_page_titles.append(title)
    # Make sure the number of page titles remained the same, otherwise raise a warning
    if len(page_title_list) == len(redirected_page_titles):
        return redirected_page_titles
    else:
        print("WARNING! The number of page titles in the redirected list ({0}) is not equal to the input list ({1})".format(len(redirected_page_titles),len(page_title_list)))
        return redirected_page_titles

def get_page_outlinks(page_title,redirects=1):
    # Replace spaces with underscores
    #page_title = page_title.replace(' ','_')
    
    bad_titles = ['Special:','Wikipedia:','Help:','Template:','Category:','International Standard','Portal:','s:']
    
    # Get the response from the API for a query
    # After passing a page title, the API returns the HTML markup of the current article version within a JSON payload
    req = requests.get('https://en.wikipedia.org/w/api.php?action=parse&format=json&page={0}&redirects={1}&prop=text&disableeditsection=1&disabletoc=1'.format(page_title,redirects))
    
    # Read the response into JSON to parse and extract the HTML
    json_string = json.loads(req.text)
    
    # Initialize an empty list to store the links
    outlinks_list = [] 
    
    if 'parse' in json_string.keys():
        page_html = json_string['parse']['text']['*']

        # Parse the HTML into Beautiful Soup
        soup = BeautifulSoup(page_html,'lxml')

        # Delete tags associated with templates
        for tag in soup.find_all('tr'):
            tag.replace_with('')

        # For each paragraph tag, extract the titles within the links
        for para in soup.find_all('p'):
            for link in para.find_all('a'):
                if link.has_attr('title'):
                    title = link['title']
                    # Ignore links that aren't interesting
                    if all(bad not in title for bad in bad_titles):
                        outlinks_list.append(title)

        # For each unordered list, extract the titles within the child links
        for unordered_list in soup.find_all('ul'):
            for item in unordered_list.find_all('li'):
                for link in item.find_all('a'):
                    if link.has_attr('title'):
                        title = link['title']
                        # Ignore links that aren't interesting
                        if all(bad not in title for bad in bad_titles):
                            outlinks_list.append(title)

    return outlinks_list

Get the outlinks.

raw_outlinks = get_page_outlinks(page_title)
redirected_outlinks = resolve_redirects(raw_outlinks)

Get the data.

This stage may take several minutes.

# Get the data
hl_pvs_df = get_multiple_pageviews(redirected_outlinks + [page_title],today_s)

# Show the top rows
hl_pvs_df.head()
Epic film Space opera Film series George Lucas Star Wars (film) 20th Century Fox Popular culture Cultural impact of Star Wars The Empire Strikes Back Return of the Jedi Star Wars sequel trilogy Academy Awards List of highest-grossing films Rogue One Media franchise Star Wars expanded universe List of Star Wars books Star Wars video games List of Star Wars comic books Fictional universe Guinness World Records The Walt Disney Company Lucasfilm Walt Disney Studios (division) Digital distribution Galaxies in fiction List of Star Wars creatures Humanoid Droid (robot) Spacefaring Galactic Republic Galactic Empire (Star Wars) New Republic (Star Wars) The Force (Star Wars) Supernatural Psychokinesis Clairvoyance Precognition Mind control Jedi Sith Star Wars opening crawl Computer-generated imagery List of changes in Star Wars re-releases Blu-ray Turner Broadcasting System Death Star Rebel Alliance Palpatine Darth Vader ... May the Force be with you Science fiction film Blockbuster (entertainment) Spaceballs Family Guy Blue Harvest Seth Green Robot Chicken: Star Wars Hardware Wars Ernie Fosselius Library of Congress National Film Registry Fan film The Official Star Wars Fan Film Awards Copyright Parody Mockumentary Star Wars canon Star Wars Holiday Special CBS Caravan of Courage: An Ewok Adventure American Broadcasting Company Ewok Micro-series Genndy Tartakovsky General Grievous Emmy Award Primetime Emmy Award for Outstanding Animated Program Cartoon Network Netflix Disney XD Star Wars Detours Brendan Hay Matthew Senreich Architecture of Star Wars Empire of Dreams Jedi census phenomenon Jediism Physics and Star Wars Star Wars Day Star Wars role play The Story of Star Wars Star Wars sources and analogues Technology in Star Wars Anchor The Science of Star Wars (book) Star Wars and History National Geographic Society Museum of Science (Boston) Star Wars
2015-07-01 575.0 881.0 473.0 3088.0 4633.0 2008.0 797.0 76.0 2602.0 2569.0 1170.0 3482.0 35121.0 15.0 400.0 363.0 1516.0 141.0 215.0 323.0 1882.0 4821.0 954.0 NaN 359.0 47.0 394.0 423.0 90.0 46.0 168.0 498.0 98.0 404.0 1094.0 1027.0 1279.0 652.0 740.0 930.0 1011.0 445.0 1342.0 571.0 1367.0 678.0 628.0 539.0 1507.0 3577.0 ... 70.0 793.0 518.0 1284.0 6991.0 487.0 3157.0 168.0 108.0 22.0 1211.0 1085.0 105.0 53.0 3373.0 737.0 681.0 586.0 566.0 2227.0 207.0 2071.0 464.0 9.0 835.0 629.0 1305.0 126.0 3014.0 9927.0 1244.0 238.0 5.0 65.0 17.0 49.0 165.0 416.0 42.0 165.0 11.0 42.0 103.0 53.0 692.0 4.0 16.0 510.0 115.0 13636.0
2015-07-02 546.0 876.0 508.0 3383.0 4700.0 2033.0 871.0 105.0 2505.0 2622.0 1233.0 3493.0 33760.0 24.0 354.0 374.0 1366.0 136.0 260.0 329.0 1788.0 4533.0 933.0 NaN 466.0 85.0 348.0 447.0 92.0 59.0 170.0 443.0 118.0 480.0 1025.0 1104.0 1180.0 643.0 696.0 801.0 1043.0 449.0 1421.0 635.0 1434.0 635.0 697.0 539.0 1446.0 3649.0 ... 102.0 970.0 522.0 1548.0 7305.0 448.0 3205.0 153.0 59.0 14.0 1378.0 912.0 98.0 36.0 3846.0 853.0 847.0 412.0 595.0 2168.0 214.0 1981.0 569.0 11.0 656.0 537.0 1202.0 67.0 2933.0 9490.0 1335.0 230.0 8.0 55.0 13.0 52.0 210.0 403.0 69.0 193.0 13.0 59.0 129.0 105.0 686.0 11.0 12.0 634.0 107.0 13901.0
2015-07-03 620.0 914.0 526.0 3186.0 4925.0 1879.0 666.0 125.0 2550.0 2780.0 1104.0 3590.0 35669.0 17.0 373.0 384.0 1380.0 180.0 224.0 336.0 1851.0 3922.0 916.0 NaN 357.0 52.0 360.0 506.0 94.0 45.0 166.0 461.0 86.0 463.0 1011.0 1043.0 1241.0 688.0 599.0 799.0 912.0 428.0 1365.0 680.0 1274.0 530.0 602.0 453.0 1337.0 3434.0 ... 66.0 863.0 549.0 1057.0 7997.0 384.0 3319.0 164.0 64.0 29.0 1218.0 951.0 81.0 37.0 2938.0 735.0 893.0 467.0 571.0 1870.0 216.0 1824.0 593.0 8.0 611.0 459.0 1284.0 91.0 2911.0 9205.0 1117.0 229.0 12.0 42.0 23.0 60.0 206.0 394.0 57.0 265.0 7.0 61.0 89.0 81.0 570.0 4.0 12.0 451.0 98.0 14129.0
2015-07-04 590.0 967.0 612.0 3386.0 5520.0 1972.0 624.0 70.0 2725.0 2793.0 1224.0 3594.0 36785.0 19.0 403.0 323.0 1465.0 149.0 213.0 305.0 1765.0 3988.0 919.0 NaN 312.0 81.0 334.0 424.0 62.0 62.0 146.0 418.0 100.0 418.0 1006.0 952.0 1144.0 621.0 671.0 799.0 849.0 375.0 1173.0 677.0 1263.0 449.0 574.0 477.0 1363.0 3819.0 ... 83.0 866.0 525.0 1550.0 6886.0 439.0 3333.0 118.0 52.0 20.0 1260.0 1020.0 104.0 41.0 2226.0 639.0 905.0 376.0 538.0 1768.0 236.0 1730.0 548.0 19.0 643.0 513.0 1177.0 68.0 2993.0 8792.0 1141.0 224.0 3.0 45.0 24.0 55.0 130.0 337.0 34.0 509.0 6.0 48.0 85.0 68.0 585.0 2.0 8.0 424.0 97.0 15633.0
2015-07-05 655.0 1023.0 695.0 5080.0 5954.0 2137.0 777.0 86.0 3202.0 3100.0 1437.0 4149.0 45487.0 26.0 387.0 345.0 1504.0 161.0 242.0 354.0 2080.0 4474.0 956.0 NaN 329.0 56.0 591.0 481.0 88.0 73.0 202.0 405.0 171.0 408.0 1175.0 1005.0 1276.0 757.0 701.0 911.0 1026.0 434.0 1772.0 718.0 1298.0 509.0 626.0 461.0 1479.0 3914.0 ... 82.0 978.0 621.0 1403.0 9069.0 472.0 3684.0 166.0 76.0 11.0 1221.0 1096.0 121.0 30.0 2516.0 755.0 838.0 466.0 624.0 2027.0 271.0 1998.0 560.0 17.0 643.0 546.0 1323.0 78.0 2927.0 9465.0 1372.0 224.0 5.0 45.0 18.0 41.0 162.0 364.0 96.0 353.0 10.0 83.0 134.0 91.0 699.0 7.0 11.0 496.0 96.0 17048.0

5 rows × 343 columns

What are the most-viewed articles in the hyperlink network?

most_viewed_articles = hl_pvs_df.cumsum().ix[str(yesterday.date())]
most_viewed_articles = most_viewed_articles.sort_values(ascending=False)
most_viewed_articles.head(10)
Star Wars                         20690177.0
World War II                      14202631.0
Adolf Hitler                      13230831.0
List of highest-grossing films    12742674.0
World War I                       12426526.0
Harry Potter                       9362149.0
Star Wars (film)                   6388663.0
Mark Hamill                        6112691.0
Napoleon                           5565914.0
Rogue One                          5309160.0
Name: 2016-10-31 00:00:00, dtype: float64

Most and least correlated articles

Which articles are most correlated with each other?

# Log the pageview data to reduce skew from bursty outliers abd make the correlation table
hl_corr_df = hl_pvs_df.apply(np.log).corr()

# Correlation table is symmetric, drop one half of them
# From: http://stackoverflow.com/questions/34417685/melt-the-upper-triangular-matrix-of-a-pandas-dataframe
hl_corr_df = hl_corr_df.where(np.triu(np.ones(hl_corr_df.shape)).astype(np.bool))

# Unstack the DataFrame into a series and sort
hl_corr_s = hl_corr_df.unstack().sort_values(ascending=False)

# Drop NaNs
hl_corr_s = hl_corr_s.dropna()

# Drop values equal to 1
hl_corr_s = hl_corr_s[hl_corr_s < 1]

List out the 10 most correlated articles.

hl_corr_s.head(10)
General Grievous  Count Dooku       0.985698
Count Dooku       Qui-Gon Jinn      0.984706
Qui-Gon Jinn      Obi-Wan Kenobi    0.984492
Star Wars         Darth Vader       0.982880
Yoda              Obi-Wan Kenobi    0.982145
Qui-Gon Jinn      Naboo             0.981697
Padmé Amidala     Darth Vader       0.981681
Qui-Gon Jinn      Yoda              0.981426
Yoda              Darth Vader       0.981169
Qui-Gon Jinn      Darth Vader       0.980497
dtype: float64

Inspect this correlation from the raw data.

_df = hl_pvs_df[list(hl_corr_s.index[0])]

ax = _df.plot(logy=True)

Look at the 10 least-correlated articles.

hl_corr_s.tail(10)
Jedi Training: Trials of the Temple  The Empire Strikes Back               -0.648298
The Story of Star Wars               Jedi Training: Trials of the Temple   -0.649527
Jedi Training: Trials of the Temple  Jedi                                  -0.652811
                                     George Lucas                          -0.657807
                                     Irvin Kershner                        -0.664598
                                     Rebel Alliance                        -0.665802
                                     Gary Kurtz                            -0.673432
                                     Leigh Brackett                        -0.688612
Blue Harvest                         Jedi Training: Trials of the Temple   -0.696662
Jedi Training: Trials of the Temple  Jabba the Hutt                        -0.698533
dtype: float64

Plot the correlation between the two most anti-correlated articles. These show some kinda wacky properties that are interesting to explore or think more about.

_df = hl_pvs_df[list(hl_corr_s.index[-1])]

ax = _df.plot(logy=True)

Is there a relationship between the position of the link on the page and the correlation between the linked article's pageviews and the seed article's pageviews? For instance, links closer to the top of the page might reflect more important topics while links towards the end of the page might be less relevant.

link_corrs = []

for num,link in enumerate(redirected_outlinks):
    try:
        link_corrs.append({'position':num,'title':link,'corr':hl_corr_s.ix[(page_title,link)]})
    except KeyError:
        print("Error on: {0}".format(link))

Plot the results.

ax = pd.DataFrame(link_corrs).plot.scatter(x='position',y='corr')
ax.set_xlim((0,len(link_corrs)))
ax.set_ylim((-1,1))
ax.set_xlabel('Link position')
ax.set_ylabel('Correlation')
<matplotlib.text.Text at 0x7f59ce9a59b0>

Get page revisions

In this section, we'll repurpose and adapt code from the last lab to get data about page revisions. Rather than looking at the number of times a user contributed to a given article, we'll simply count the number of times the article was edited on a given date.

def get_page_edits_by_date(page_title,conn,date_string='2014-12-31'):
    """ Takes a page title and returns the number of revisions made on each date.
      page_title = a string for the page title to get its revisions
      date_string = a string for the date in YYYY-MM-DD format
      conn = a database connection
      
    Returns:
      A DataFrame with username, page title, edit count, and min/max timestamps
    """
    # In case you pass a page title with spaces in it, replace the spaces with underscores
    page_title = page_title.replace(' ','_').encode('utf8').decode('latin1')
    
    # The MySQL query string used to retrieve the data. By line, it is
    ## converting the timestamp to a date and 
    ## counting the number of elements
    ## from the "revisions" table
    ## joining the "page" table on it
    ## using the page_id and rev_page columns as keys
    ## limiting the results to entries that have the pagetitle, 
    ## occur in the namespace, and happen after Dec 31, 2014
    ## grouping the results by date
    s = """
            SELECT
                DATE(rev_timestamp) as date,
                page_title,
                COUNT(*) as edits
            FROM 
                revision 
            JOIN 
                page ON page.page_id = revision.rev_page
            WHERE 
                page.page_title = "{0}" 
                AND page_namespace = 0
                AND DATE(rev_timestamp) > '{1}'
            GROUP BY
                date
        """.format(page_title,date_string)

    # Use the connection to run the query and return the results as a DataFrame
    _df = pd.read_sql_query(s,conn)
    
    _df['page_title'] = _df['page_title'].str.decode('utf8')
    _df['page_title'] = _df['page_title'].str.replace('_',' ')
    
    # Return the data, with a clean index
    return _df

def get_neighbors_revisions(page_title,conn):
    """ Takes a page title and returns revisions for the page and its neighbors.
      page_title = a string for the page title to get its revisions
      
    Returns:
      A pandas DataFrame containing all the page revisions.
    """
    # Get the outlinks from the page and include the page itself in the list
    alters = get_page_outlinks(page_title) + [page_title]
    # Resolve the redirects in the list of alters
    alters = list(set(resolve_redirects(alters)))
    # Create an empty container to hold the DataFrames
    df_list = []
    # For each page, get the revision counts and append to the df_list
    for alter in alters:
        _df = get_page_edits_by_date(alter,conn)
        df_list.append(_df)
    # Concatenate the list of revision count DataFrames into a giant DataFrame
    df = pd.concat(df_list)
    # Return the data
    return df.reset_index(drop=True)

Get the authentication information and connect to the database.

host, user, password = os.environ['MYSQL_HOST'], os.environ['MYSQL_USERNAME'], os.environ['MYSQL_PASSWORD']
conn = pymysql.connect(host=host,user=user,password=password,database='enwiki_p',connect_timeout=3600)
conn.cursor().execute('use enwiki_p');

Get the number of revisions per day for all the articles.

hl_daily_rev_df = get_neighbors_revisions(page_title,conn)
hl_daily_rev_df.head()
date page_title edits
0 2015-03-21 Dagobah 1.0
1 2015-05-17 Dagobah 1.0
2 2015-10-09 Dagobah 1.0
3 2015-10-22 Dagobah 1.0
4 2015-10-26 Dagobah 1.0

Reindex the edit data so it's starting and ending on the same dates as the pageviews data.

# Convert into a format like the hl_pageviews DataFrame
# Index are dates between Jan 1, 2015 and today; columns are article titles; values are number of edits
hl_edits_df = hl_daily_rev_df.set_index(['date','page_title'])['edits'].unstack(1)

# Reindex so dates are continuous
pv_start_ix = str(hl_pvs_df.index.min().date())
_date_range = pd.date_range(pv_start_ix,yesterday_date_s)
hl_edits_df = hl_edits_df.reindex(index=_date_range)

# Fill in empty observations with 0s
hl_edits_df = hl_edits_df.fillna(0)

hl_edits_df.head()
page_title 20th Century Fox 3D film Academy Awards Academy of Motion Picture Arts and Sciences Adolf Hitler Akira Kurosawa Al Williamson Alan Dean Foster Alan F. Horn Alden Ehrenreich Alderaan Alien (film) American Broadcasting Company American Graffiti Amy Hennig Anamorphic format Anchor Anthony Daniels Apocalyptic and post-apocalyptic fiction Archie Goodwin (comics) Architecture of Star Wars Argentina Arri Art film Aspect ratio (image) Atari 2600 BB-8 Bad Robot Productions Bantam Books Ben Burtt Ben Mendelsohn Bespin Billy Dee Williams Blade Runner Blockbuster (entertainment) Blu-ray Blue Harvest Bob Anderson (fencer) Bob Iger Boba Fett Bradford Young Brendan Hay Brian Daley Bryan Burk C-3PO CBS Cam Kennedy Canon (fiction) Caravan of Courage: An Ewok Adventure Carmine Infantino ... Stormtrooper Stormtrooper (Star Wars) Sturmabteilung Supernatural THX TIE fighter Tag and Bink Tataouine Tatooine Technology in Star Wars Technology in science fiction The Empire Strikes Back The Force (Star Wars) The Hidden Fortress The Hollywood Reporter The Holocaust The New Jedi Order The Official Star Wars Fan Film Awards The Science of Star Wars (book) The Story of Star Wars The Walt Disney Company The Young Indiana Jones Chronicles Thrawn trilogy Time (magazine) Timothy Zahn Tokyo Disneyland Tom Veitch Tomorrowland Terrace Topps Trading card Turner Broadcasting System Universal Parks & Resorts Universal Studios Variety (magazine) Video game Walt Disney Imagineering Walt Disney Parks and Resorts Walt Disney Studios (division) Walt Disney World Walt Simonson Wehrmacht Whilce Portacio Wii Wookiee World War I World War II Xbox 360 Xbox One Yavin Yoda
2015-07-01 2.0 0.0 0.0 0.0 2.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 1.0 0.0 0.0 0.0 0.0 0.0 0.0 1.0 0.0 0.0 0.0 0.0 0.0 1.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 1.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 2.0 0.0 0.0 0.0 0.0 0.0 ... 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 2.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 1.0 0.0 0.0 4.0 0.0 4.0
2015-07-02 0.0 0.0 0.0 0.0 1.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 1.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 1.0 0.0 0.0 0.0 0.0 1.0 0.0 0.0 4.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 2.0 0.0 0.0 0.0 0.0 0.0 ... 0.0 0.0 3.0 0.0 0.0 0.0 0.0 0.0 1.0 8.0 1.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 1.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 1.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 1.0 0.0 0.0 0.0 2.0
2015-07-03 0.0 0.0 0.0 0.0 1.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 1.0 0.0 0.0 1.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 ... 0.0 0.0 0.0 0.0 7.0 0.0 0.0 0.0 0.0 0.0 0.0 2.0 0.0 0.0 0.0 1.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0
2015-07-04 0.0 0.0 0.0 1.0 1.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 2.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 ... 0.0 0.0 0.0 0.0 3.0 0.0 0.0 0.0 0.0 3.0 1.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 2.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0
2015-07-05 0.0 0.0 0.0 0.0 1.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 1.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 ... 0.0 0.0 0.0 4.0 0.0 0.0 0.0 0.0 0.0 4.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 1.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 2.0 0.0 0.0

5 rows × 341 columns

Are pageviews and edits correlated with each other?

_s1 = hl_pvs_df[page_title]
_s2 = hl_edits_df[page_title]

np.corrcoef(_s1.apply(np.log),_s2)[0][1]
0.35661013740675535
single_pv_edits_df = pd.DataFrame({'pageviews':_s1,'edits':_s2})
ax = single_pv_edits_df.plot(secondary_y='edits',logy=True)
ax.right_ax.set_yscale('log')
ax.set_ylabel('Pageviews')
ax.right_ax.set_ylabel('Edits')
<matplotlib.text.Text at 0x7f59cdc05a20>

Can Wikipedia supply information to keep up with demand?

The ratio between the cumulative pageviews and cumulative edits.

ax = (_s1.cumsum()/_s2.cumsum()).plot()

ax.set_ylabel('Cumulative pageviews per edit')
<matplotlib.text.Text at 0x7f59cdd14470>
def zscore(series):
    return np.abs((series - series.mean())/series.std())

Look at the normalized (z-score) excitation and relaxation in edits and pageviews by day. Each point is a single day in the article's history and they're connected if they come one day after each other. Values along the diagonal in red suggest that increases in attention to the article are matched by similar increases in editing activity on the article. Alternatively, data points in the upper-left triangle suggest increases in pageviews are not matched by increases in edits while data points in the lower-right triangle suggest increases in edits are not matched by increases in pageviews.

f,ax = plt.subplots(1,1)

ax.set_xlabel('Edits (z-score)')
ax.set_ylabel('Pageviews (z-score)')
ax.set_xlim((1e-3,1e2))
ax.set_ylim((1e-3,1e2))
ax.set_xscale('log')
ax.set_yscale('log')

plt.text(1e-1,1e1,'More views than edits',ha='center',weight='bold')
plt.text(1e1,1e-1,'More edits than views',ha='center',weight='bold')

plt.plot([1e-3,1e2],[1e-3,1e2],axes=ax,c='r')

_s1 = zscore(hl_edits_df[page_title])
_s2 = zscore(hl_pvs_df[page_title])
plt.plot(_s1,_s2,'o-',axes=ax,c='grey');