Lab 1 - Revision Histories

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 first of five lab notebooks that will explore how to do some introductory data extraction and analysis from Wikipedia data. This lab will use a combination of MySQL and Python to retrieve the revision histories for a selection of articles. 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 basic Python commands work

a = 2
b = 2
a+b
4
list(range(0,5))
[0, 1, 2, 3, 4]
your_name = 'Alex Bozanic'
print("Hello, {0}".format(your_name))
Hello, Alex Bozanic

Import modules and setup environment

Load up all the libraries we'll need to connect to the database, retrieve information for analysis, and visualizing 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/

# 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
/srv/paws/lib/python3.4/site-packages/matplotlib/font_manager.py:273: UserWarning: Matplotlib is building the font cache using fc-list. This may take a moment.
  warnings.warn('Matplotlib is building the font cache using fc-list. This may take a moment.')
/srv/paws/lib/python3.4/site-packages/matplotlib/font_manager.py:273: UserWarning: Matplotlib is building the font cache using fc-list. This may take a moment.
  warnings.warn('Matplotlib is building the font cache using fc-list. This may take a moment.')

Setup a connection to the English Wikipedia database

Retrieve the host name, username, and (encrypted) password associated with your account so you can login to the database.

host, user, password = os.environ['MYSQL_HOST'], os.environ['MYSQL_USERNAME'], os.environ['MYSQL_PASSWORD']

Connect to the system using the creditials from above, then select the database for the English Wikipedia.

conn = pymysql.connect(host=host,user=user,password=password,database='enwiki_p',connect_timeout=3600)
conn.cursor().execute('use enwiki_p');

What tables are available for use?

pd.read_sql_query('show tables',conn)
Tables_in_enwiki_p
0 abuse_filter
1 abuse_filter_action
2 abuse_filter_log
3 aft_article_answer
4 aft_article_answer_text
5 aft_article_feedback
6 aft_article_feedback_properties
7 aft_article_feedback_ratings_rollup
8 aft_article_feedback_select_rollup
9 aft_article_field
10 aft_article_field_group
11 aft_article_field_option
12 aft_article_filter_count
13 aft_article_revision_feedback_ratings_rollup
14 aft_article_revision_feedback_select_rollup
15 archive
16 archive_userindex
17 article_feedback
18 article_feedback_pages
19 article_feedback_properties
20 article_feedback_ratings
21 article_feedback_revisions
22 article_feedback_stats
23 article_feedback_stats_types
24 category
25 categorylinks
26 change_tag
27 ep_articles
28 ep_cas
29 ep_courses
30 ep_events
31 ep_instructors
32 ep_oas
33 ep_orgs
34 ep_revisions
35 ep_students
36 ep_users_per_course
37 externallinks
38 filearchive
39 filearchive_userindex
40 flaggedimages
41 flaggedpage_config
42 flaggedpage_pending
43 flaggedpages
44 flaggedrevs
45 flaggedrevs_promote
46 flaggedrevs_statistics
47 flaggedrevs_stats
48 flaggedrevs_stats2
49 flaggedrevs_tracking
50 flaggedtemplates
51 geo_tags
52 global_block_whitelist
53 hitcounter
54 image
55 imagelinks
56 interwiki
57 ipblocks
58 ipblocks_ipindex
59 iwlinks
60 l10n_cache
61 langlinks
62 localisation
63 localisation_file_hash
64 logging
65 logging_logindex
66 logging_userindex
67 mark_as_helpful
68 math
69 module_deps
70 msg_resource_links
71 oldimage
72 oldimage_userindex
73 page
74 page_props
75 page_restrictions
76 pagelinks
77 pagetriage_log
78 pagetriage_page
79 pagetriage_page_tags
80 pagetriage_tags
81 pif_edits
82 povwatch_log
83 povwatch_subscribers
84 protected_titles
85 recentchanges
86 recentchanges_userindex
87 redirect
88 revision
89 revision_userindex
90 site_identifiers
91 site_stats
92 sites
93 tag_summary
94 templatelinks
95 transcode
96 updatelog
97 updates
98 user
99 user_former_groups
100 user_groups
101 user_properties
102 user_properties_anon
103 valid_tag
104 watchlist_count
105 wbc_entity_usage
106 wikilove_image_log
107 wikilove_log
s = """
        SELECT 
            *
        FROM 
            recentchanges_userindex
        LIMIT
            5
    """
    
pd.read_sql_query(s,conn)
rc_id rc_timestamp rc_cur_time rc_user rc_user_text rc_namespace rc_title rc_comment rc_minor rc_bot rc_new rc_cur_id rc_this_oldid rc_last_oldid rc_type rc_source rc_patrolled rc_ip rc_old_len rc_new_len rc_deleted rc_logid rc_log_type rc_log_action rc_params
0 858164191 b'20160903224602' b'' 6046894 b'Editor2020' 14 b'Personality_disorders' b'update with info from article' 0 0 0 1391554 737605529 701709968 0 b'mw.edit' 0 None 1009.0 645.0 0 0 None b'' b''
1 858164192 b'20160903224602' b'' 21844114 b'Billgatenguyenlobcity' 0 b'VFW_Sport_Clips_Help_a_Hero_200' b'' 0 0 0 5492270 737605530 736667403 0 b'mw.edit' 0 None 12255.0 12381.0 0 0 None b'' b''
2 858164194 b'20160903224603' b'' 25977978 b'Majora' 3 b'72.143.87.158' b'/* Your request at Files for upload */ Decli... 0 0 0 51506372 737605531 737604856 0 b'mw.edit' 0 None 491.0 535.0 0 0 None b'' b''
3 858164195 b'20160903224602' b'' 161142 b'RHaworth' 6 b'Show_Me_How_You_Burlesque.jpg' b'[[WP:CSD#F9|F9]]: Media file [[WP:COPYVIO|co... 0 0 0 51422353 0 0 3 b'mw.log' 1 None NaN NaN 0 77123019 b'delete' b'delete' b'a:0:{}'
4 858164196 b'20160903224604' b'' 0 b'197.211.57.55' 0 b'Miami_(Damien_Saez_album)' b'/* References */' 0 0 0 39340982 737605532 737605423 0 b'mw.edit' 0 None 3688.0 3607.0 0 0 None b'' b''

Important note

Article page titles need to be separated by underscores "_" rather than spaces. It's easy to replace spaces with underscores using the replace method called on the string.

page_title = 'Rothschild family'.replace(' ','_')
page_title
'Rothschild_family'

Get revisions for a single article

Write a function get_page_revisions that takes the name of a Wikipedia page and its namespace and use the database connection to return a pandas DataFrame containing all the revisions for the article. Some of the fields inside needs to be cleaned up by converting to other data types to help with analysis in later steps.

def get_page_revisions(page_title,namespace,conn):
    """ Takes a page title and returns its revision history.
      page_title = a string for the page title to get its revisions
      namespace = an int to get the revisions from a specific namespace
      conn = a database connection
      
    Returns:
      A pandas DataFrame containing all the article revisions and page information
    """
    # In case you pass a page title with spaces in it, replace the spaces with underscores
    page_title = page_title.replace(' ','_')

    # The MySQL query string used to retrieve the data. By line, it is
    ## selecting all columns 
    ## 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 occur in the namespace and pagetitle
    ## and ordering the results by the timestamp
    s = """
            SELECT 
                *
            FROM 
                revision 
            JOIN 
                page ON page.page_id = revision.rev_page
            WHERE 
                page.page_namespace = {1} AND page.page_title = '{0}' 
            ORDER BY 
                revision.rev_timestamp ASC
        """.format(page_title,namespace)
    
    # Use the connection to run the query and return the results as a DataFrame
    _df = pd.read_sql_query(s,conn)

    # Some of the results have a "bytestring" format
    byte_columns = ['rev_comment','rev_user_text','rev_timestamp','rev_sha1','page_content_model',
                    'page_title','page_restrictions','page_touched','page_links_updated']
    
    # For each column, convert it from bytestring to a utf8 string
    for col in byte_columns:
        _df[col] = _df[col].str.decode('utf8')

    # Several of the columns are timestamps. Convert to datetimes
    _df['rev_timestamp'] = _df['rev_timestamp'].apply(lambda x:pd.datetime.strptime(x,'%Y%m%d%H%M%S'))
    _df['page_touched'] = _df['page_touched'].apply(lambda x:pd.datetime.strptime(x,'%Y%m%d%H%M%S'))
    _df['page_links_updated'] = _df['page_links_updated'].apply(lambda x:pd.datetime.strptime(x,'%Y%m%d%H%M%S'))
    
    # Return the data
    return _df

Use the function to get the revisions for a single article and use the .head() method to inspect the first 5 rows in the DataFrame.

rev_df = get_page_revisions('Rothschild family',0,conn)
rev_df.head()
rev_id rev_page rev_text_id rev_comment rev_user rev_user_text rev_timestamp rev_minor_edit rev_deleted rev_len rev_parent_id rev_sha1 rev_content_model rev_content_format page_id page_namespace page_title page_restrictions page_counter page_is_redirect page_is_new page_random page_touched page_links_updated page_latest page_len page_content_model
0 646407 179855 0 0 212.108.208.141 2003-02-06 08:59:54 0 0 143 0 0ezqcdigvu4rv9az3ze4qgp2kb64squ None None 179855 0 Rothschild_family 0 0 0 0.181589 2016-10-03 01:40:20 2016-10-03 01:40:21 742325179 90820 wikitext
1 1206470 179855 0 change stub to different stub 0 62.253.64.7 2003-02-06 10:37:23 0 0 634 646407 n64gxue5d7ufuqurnz330ggvhwqx8yf None None 179855 0 Rothschild_family 0 0 0 0.181589 2016-10-03 01:40:20 2016-10-03 01:40:21 742325179 90820 wikitext
2 1249000 179855 0 0 24.67.8.93 2003-07-28 00:58:14 0 0 640 1206470 1khu0b6icwlcpkxn8f6p4uz0a2pc22k None None 179855 0 Rothschild_family 0 0 0 0.181589 2016-10-03 01:40:20 2016-10-03 01:40:21 742325179 90820 wikitext
3 1249004 179855 0 16924 Maximus Rex 2003-08-06 08:16:33 0 0 813 1249000 3knzdp74w5qepdvflfr2iy9pliwityd None None 179855 0 Rothschild_family 0 0 0 0.181589 2016-10-03 01:40:20 2016-10-03 01:40:21 742325179 90820 wikitext
4 1249005 179855 0 16924 Maximus Rex 2003-08-06 08:17:18 0 0 814 1249004 h30y20xz54kjfoxukgv65muzu21hk0c None None 179855 0 Rothschild_family 0 0 0 0.181589 2016-10-03 01:40:20 2016-10-03 01:40:21 742325179 90820 wikitext

Count the total number of revisions in the article.

len(rev_df)
4522

Count the total number of unique users contributing to the article.

len(rev_df['rev_user_text'].unique())
1711

When was the first revision made to the article?

rev_df['rev_timestamp'].min()
Timestamp('2003-02-06 08:59:54')

When was the most recent revision made to the article?

rev_df['rev_timestamp'].max()
Timestamp('2016-10-03 01:40:20')

How has the size of the article changed over time?

ax = rev_df['rev_len'].plot()
ax.set_xlabel('Revisions')
ax.set_ylabel('Article size (bytes)')
<matplotlib.text.Text at 0x7fbc6729a780>

Who made the largest change to the article?

# Use the idxmax() method to return the index value for the largest value in the series
loc_max_revision = rev_df['rev_len'].idxmax()

# Show the values of a single row
rev_df.ix[loc_max_revision]
rev_id                                            450858575
rev_page                                             179855
rev_text_id                                               0
rev_comment           Detailed History of Rothschild family
rev_user                                           15347830
rev_user_text                                      OhioLeda
rev_timestamp                           2011-09-16 19:48:39
rev_minor_edit                                            1
rev_deleted                                               0
rev_len                                              193772
rev_parent_id                                     450849066
rev_sha1                    jrt8tuue3eb2tp2spv741hpayweax3k
rev_content_model                                      None
rev_content_format                                     None
page_id                                              179855
page_namespace                                            0
page_title                                Rothschild_family
page_restrictions                                          
page_counter                                              0
page_is_redirect                                          0
page_is_new                                               0
page_random                                        0.181589
page_touched                            2016-10-03 01:40:20
page_links_updated                      2016-10-03 01:40:21
page_latest                                       742325179
page_len                                              90820
page_content_model                                 wikitext
Name: 2610, dtype: object

Go inspect what this largest revision was. Actually this specific example is extremely NSFW.

rev_id = rev_df.ix[loc_max_revision,'rev_id']
print('https://en.wikipedia.org/w/index.php?oldid={0}'.format(rev_id))
https://en.wikipedia.org/w/index.php?oldid=450858575

Group revisions by date

Muliple revisions can be made in a single day. We want to be able to count the number of revisions per day and how the article's length has changed over time.

# For each timestamp extract only its date (ignoring the time of day) 
# and save as a new column "rev_date"
rev_df['rev_date'] = rev_df['rev_timestamp'].apply(lambda x:x.date())

# Compare the full "rev_timestamp" to the new "rev_date"
rev_df[['rev_timestamp','rev_date']].head()
rev_timestamp rev_date
0 2003-02-06 08:59:54 2003-02-06
1 2003-02-06 10:37:23 2003-02-06
2 2003-07-28 00:58:14 2003-07-28
3 2003-08-06 08:16:33 2003-08-06
4 2003-08-06 08:17:18 2003-08-06

What dates had the most revisions in a single day? A simple way of doing this is to count the number of times each "rev_date" occurs in the data with the value_counts method. Let's look at the top 10, 5 of which are in October 2012 in the weeks before the Election Day.

rev_df['rev_date'].value_counts().head(10)
2009-12-03    90
2009-12-19    64
2009-12-11    46
2009-12-08    39
2009-12-05    33
2011-12-09    30
2009-12-09    28
2009-12-15    27
2011-03-27    25
2009-12-07    24
Name: rev_date, dtype: int64

We can use the groupby functionality to create "baby" DataFrames having all the same particular value. For example, we can group by the date and each of the baby DataFrames would be all the revisions that occurred on that date. Store the groupby in the "rev_gb_date" object for subsequent steps.

Inspect a single baby DataFrame by passing the key (the date values we grouped on) to the get_group method and look at the first 5 entries.

rev_gb_date = rev_df.groupby(['rev_date'])

_date = pd.Timestamp('2009-12-03').date()
rev_gb_date.get_group(_date).head(5)
rev_id rev_page rev_text_id rev_comment rev_user rev_user_text rev_timestamp rev_minor_edit rev_deleted rev_len rev_parent_id rev_sha1 rev_content_model rev_content_format page_id page_namespace page_title page_restrictions page_counter page_is_redirect page_is_new page_random page_touched page_links_updated page_latest page_len page_content_model rev_date
1129 329382046 179855 0 /* Elevated to the nobility */ 0 86.26.0.25 2009-12-03 03:43:18 0 0 25172 328283056 orgw3hczotk6eulcnroqnba7wpxpmq6 None None 179855 0 Rothschild_family 0 0 0 0.181589 2016-10-03 01:40:20 2016-10-03 01:40:21 742325179 90820 wikitext 2009-12-03
1130 329382393 179855 0 /* Austrian branch */ detail 0 86.26.0.25 2009-12-03 03:45:23 0 0 25239 329382046 qmwi3sy25frmj8iudh3ox02w869wmvt None None 179855 0 Rothschild_family 0 0 0 0.181589 2016-10-03 01:40:20 2016-10-03 01:40:21 742325179 90820 wikitext 2009-12-03
1131 329382717 179855 0 /* Prominent descendants of Mayer Amschel Roth... 0 86.26.0.25 2009-12-03 03:47:25 0 0 25323 329382393 rl9njb8pcajtym8bl1ygh94xo4osaj6 None None 179855 0 Rothschild_family 0 0 0 0.181589 2016-10-03 01:40:20 2016-10-03 01:40:21 742325179 90820 wikitext 2009-12-03
1132 329383560 179855 0 /* Austrian branch */ 0 86.26.0.25 2009-12-03 03:52:11 0 0 25477 329382717 dqwitlhkpj0sonvsnqku84jwyn7oao9 None None 179855 0 Rothschild_family 0 0 0 0.181589 2016-10-03 01:40:20 2016-10-03 01:40:21 742325179 90820 wikitext 2009-12-03
1133 329383611 179855 0 /* Austrian branch */ 0 86.26.0.25 2009-12-03 03:52:28 0 0 25482 329383560 5esur60ku5kb7m0ydcfl3k6a8d9zn1n None None 179855 0 Rothschild_family 0 0 0 0.181589 2016-10-03 01:40:20 2016-10-03 01:40:21 742325179 90820 wikitext 2009-12-03

Compute unique revisions per day

We can also use aggregate functionality to perform computations efficiently across all the baby DataFrames.

daily_revs = rev_gb_date.agg({'rev_id':pd.Series.nunique})
daily_revs.head() 
rev_id
rev_date
2003-02-06 2
2003-07-28 1
2003-08-06 3
2003-08-08 2
2003-08-13 1

Reindex the axis to make it continuous over the date range.

# Compute the first and last days revisions were observed
_min, _max = daily_revs.index.min(), daily_revs.index.max()

# Create a new index that is continuous over the whoel date range
_ix = pd.date_range(_min,_max)

# Reindex the daily revisions over the continuous date range filling in the blanks with 0s
daily_revs_reindexed = daily_revs.reindex(_ix).fillna(0)
daily_revs_reindexed.head()
rev_id
2003-02-06 2.0
2003-02-07 0.0
2003-02-08 0.0
2003-02-09 0.0
2003-02-10 0.0

What was the most active day of editing?

daily_revs_reindexed['rev_id'].sort_values(ascending=False).head(5)
2009-12-03    90.0
2009-12-19    64.0
2009-12-11    46.0
2009-12-08    39.0
2009-12-05    33.0
Name: rev_id, dtype: float64

Plot the number of revisions by day.

ax = daily_revs_reindexed['rev_id'].plot(lw=.5)

# Label the axes
ax.set_xlabel('Date')
ax.set_ylabel('Revisions')
<matplotlib.text.Text at 0x7fbc6711aba8>

This is pretty noisy. We can clean it up by applying a rolling mean over a 60-day window.

smoothed_s = daily_revs_reindexed['rev_id'].rolling(60).mean()
ax = smoothed_s.plot(lw=3)

# Label the axes
ax.set_xlabel('Date')
ax.set_ylabel('Revisions')
<matplotlib.text.Text at 0x7fbc62933710>

Plot the cumulative sum of the number of revisions over time using the cumsum method.

ax = daily_revs_reindexed['rev_id'].cumsum().plot(lw=2)

# Label the axes
ax.set_xlabel('Date')
ax.set_ylabel('Cumulative Revisions')
<matplotlib.text.Text at 0x7fbc66f9b5c0>

Compute article length by day

Using the same "rev_gb_date" object, aggregate each of the baby DataFrames and compute the median article size ("rev_len"). Reindex again to make a continuous time axis.

daily_length = rev_gb_date.agg({'rev_len':np.median})

# Reindex
daily_length_reindexed = daily_length.reindex(_ix).fillna(method='ffill')
daily_length_reindexed.head()
rev_len
2003-02-06 388.5
2003-02-07 388.5
2003-02-08 388.5
2003-02-09 388.5
2003-02-10 388.5

Plot the reindexed series, making the y-axis be on a log scale to pick up detail in the early days when the article was orders of magnitude smaller.

ax = daily_length_reindexed['rev_len'].plot(lw=2,logy=True)

# Label the axes
ax.set_xlabel('Date')
ax.set_ylabel('Article size  (bytes)')
<matplotlib.text.Text at 0x7fbc67039a90>

Compute diffs on time and article size

The "rev_len" only records the length of the revision at that point in time. By taking the difference with the previous observation, we can compute how much net content the user added or removed from the previous revision. Using the diff method on the "rev_len" series, we store the resulting differences as "rev_len_diff".

Compare the first five elements of the two series to verify it's worked as intended.

# Compute the diff and store as a new series
rev_df['rev_len_diff'] = rev_df['rev_len'].diff()

# Verify the differences are accurate
rev_df[['rev_len','rev_len_diff']].head()
rev_len rev_len_diff
0 143 NaN
1 634 491.0
2 640 6.0
3 813 173.0
4 814 1.0

Do some more cleanup of the diffs. In particular, when a revision is deleted (which is rare) the "rev_len" value is null, which makes the diff null as well. Make the first revision's "rev_len_diff" equal to the size of the article and then ffill the other nan values.

# Set the revision lengths for the null rows to be the previous value
rev_df['rev_len'] = rev_df['rev_len'].fillna(method='ffill')

# Compute the diffs again 
rev_df['rev_len_diff'] = rev_df['rev_len'].diff()

# Set the value for the first rev_len_diff to be the size of the rev_len
rev_df.loc[0,'rev_len_diff'] = rev_df.loc[0,'rev_len']

# Verify the differences are accurate
rev_df[['rev_len','rev_len_diff']].head()
rev_len rev_len_diff
0 143 143.0
1 634 491.0
2 640 6.0
3 813 173.0
4 814 1.0

Similarly, the "rev_timestamp" series only records the time when the revision occurred. By taking the difference with the previous revision, we can compute how much time has elapsed since the last edit. Using the diff method again on the "rev_timestamp" series, we store the resulting differences as "ref_timestamp_diff".

The resulting values are Timedeltas which we convert back to number of day floats by dividing by np.timedelta64.

Compare the first five elements of the two series to verify it's worked as intended.

# Compute the diff and store as a new series
rev_df['rev_timestamp_diff'] = rev_df['rev_timestamp'].diff()

# Convert the values of the new series to floats by dividing by 1 day time delta.
rev_df['rev_timestamp_diff'] = rev_df['rev_timestamp_diff'].apply(lambda x:x/np.timedelta64(1,'D'))

# Verify the differences are accurate.
rev_df[['rev_timestamp','rev_timestamp_diff']].head()
rev_timestamp rev_timestamp_diff
0 2003-02-06 08:59:54 NaN
1 2003-02-06 10:37:23 0.067697
2 2003-07-28 00:58:14 171.597813
3 2003-08-06 08:16:33 9.304387
4 2003-08-06 08:17:18 0.000521

Combine all the computations with one daily DataFrame

Because we added new series to the "rev_df" we need to re-run the groupby to update it. We can also combine all the different aggregate functions we did before into one step by defining an "agg_dict" that applies an aggregation function over the values in a specific column. This will return a DataFrame with only a subset of columns with the aggregated values we specified.

# Groupby again
rev_gb_date = rev_df.groupby(['rev_date'])

# Define an aggregation mapping of functions to columns names
agg_dict_date = {'rev_id':pd.Series.nunique,
                  'rev_len':np.median,
                  'rev_len_diff':np.median,
                  'rev_timestamp_diff':np.mean
                 }

# Execiute the aggregation functions on the groupby object
rev_agg_date = rev_gb_date.agg(agg_dict_date)

# Reindex to continuous dates
rev_agg_date = rev_agg_date.reindex(_ix)

# Fill in the resulting values of the reindexed and aggregated "rev_len" from the last value
rev_agg_date[['rev_len']] = rev_agg_date[['rev_len']].fillna(method='ffill')

# Fill in the resulting values of the reindexed and aggregated other series as 0s.
rev_agg_date[['rev_id','rev_len_diff']] = rev_agg_date[['rev_id','rev_len_diff']].fillna(0)
#rev_agg_date[['rev_id','rev_len_diff','rev_timestamp_diff']] = rev_agg_date[['rev_id','rev_len_diff','rev_timestamp_diff']].fillna(0)

# Show the first 10 values to verify it's worked as intended
rev_agg_date.tail(10)
rev_id rev_len_diff rev_len rev_timestamp_diff
2016-09-24 0.0 0.0 90470.0 NaN
2016-09-25 0.0 0.0 90470.0 NaN
2016-09-26 0.0 0.0 90470.0 NaN
2016-09-27 0.0 0.0 90470.0 NaN
2016-09-28 4.0 -2.5 90469.5 1.868631
2016-09-29 2.0 0.0 90492.5 0.535428
2016-09-30 2.0 0.0 90464.0 0.148385
2016-10-01 0.0 0.0 90464.0 NaN
2016-10-02 0.0 0.0 90464.0 NaN
2016-10-03 1.0 350.0 90820.0 2.928368

Plot the changes in the average time since the last revision by day.

_s = rev_agg_date['rev_timestamp_diff']
ax = _s.plot(logy=True)
ax.set_xlabel('Date')
ax.set_ylabel('Average time since last edit (Days)')
<matplotlib.text.Text at 0x7fbc66f20400>

That's pretty noisy. We can apply the rolling method over a 60-day window and get the mean to smooth out some of the noise.

_s = rev_agg_date['rev_timestamp_diff'].fillna(0).rolling(60).mean()
ax = _s.plot()
ax.set_xlabel('Date')
ax.set_ylabel('Average time since last edit (Days)')
<matplotlib.text.Text at 0x7fbc66c16630>

Similarly, what was the median size of a change to the article over time?

_s = rev_agg_date['rev_len_diff']
ax = _s.plot(lw=.5)
ax.set_xlabel('Date')
ax.set_ylabel('Median size of revision')
ax.set_yscale('symlog')

Again, pretty noisy. We can cleanup with a rolling mean over a 60-day window.

_s = rev_agg_date['rev_len_diff'].rolling(60).mean()
ax = _s.plot()
ax.set_xlabel('Date')
ax.set_ylabel('Median size of revision')
<matplotlib.text.Text at 0x7fbc6624d4e0>

Top editors on the article

Which editors made the most contributions to the article?

top_users = rev_df['rev_user_text'].value_counts()
top_users.head(10)
Avaya1         454
86.26.0.25     400
82.26.0.138    266
Mervyn          89
ClueBot NG      66
Favonian        55
Bender235       46
Fat&Happy       40
Vexorg          38
JillandJack     32
Name: rev_user_text, dtype: int64

This extremely skewed distribution of activity is characteristic of many online participation patterns: the "long tail" where less than 20% of users are responsible for more than 20% of contributions.

rev_count_occurrences = top_users.value_counts().reset_index()
rev_count_occurrences = rev_count_occurrences.rename(columns={'index':'Revision count','rev_user_text':'Occurrences'})
rev_count_occurrences.head()
Revision count Occurrences
0 1 1197
1 2 275
2 3 97
3 4 48
4 5 21

Plot the resulting distribution on log-log axes to see the shape of the long-tail distribution.

rev_count_occurrences.plot(x='Revision count',y='Occurrences',kind='scatter',logy=True,logx=True,s=50)
<matplotlib.axes._subplots.AxesSubplot at 0x7fbc660349e8>

Group revisions by users

We can also use the groupby-aggregate framework to group all the revisions together by the users who made them, rather than grouping revisions by the date as we did before.

rev_gb_user = rev_df.groupby(['rev_user_text'])

Look at a baby DataFrame within the groupby for a single user. These are all the revisions made by this user to this article.

rev_gb_user.get_group('Avaya1').head()
rev_id rev_page rev_text_id rev_comment rev_user rev_user_text rev_timestamp rev_minor_edit rev_deleted rev_len rev_parent_id rev_sha1 rev_content_model rev_content_format page_id page_namespace page_title page_restrictions page_counter page_is_redirect page_is_new page_random page_touched page_links_updated page_latest page_len page_content_model rev_date rev_len_diff rev_timestamp_diff
1144 329388278 179855 0 /* Elevated to the nobility */ 1755816 Avaya1 2009-12-03 04:21:28 0 0 25830 329387429 m9ka9laltciyb72rx7hclowvc82w2t1 None None 179855 0 Rothschild_family 0 0 0 0.181589 2016-10-03 01:40:20 2016-10-03 01:40:21 742325179 90820 wikitext 2009-12-03 68.0 0.003669
1145 329391148 179855 0 /* French branches */ 1755816 Avaya1 2009-12-03 04:39:14 0 0 25928 329388278 er7uyz90yf2jep854qbiudh005b3284 None None 179855 0 Rothschild_family 0 0 0 0.181589 2016-10-03 01:40:20 2016-10-03 01:40:21 742325179 90820 wikitext 2009-12-03 98.0 0.012338
1146 329391287 179855 0 /* French branches */ 1755816 Avaya1 2009-12-03 04:40:01 0 0 25949 329391148 jxxl0xfbsppzak1408hgrae35bfp04b None None 179855 0 Rothschild_family 0 0 0 0.181589 2016-10-03 01:40:20 2016-10-03 01:40:21 742325179 90820 wikitext 2009-12-03 21.0 0.000544
1147 329391543 179855 0 /* Modern business */ 1755816 Avaya1 2009-12-03 04:41:41 0 0 25982 329391287 dsolcxyprjgyjlqbn2urvkm9nycshs3 None None 179855 0 Rothschild_family 0 0 0 0.181589 2016-10-03 01:40:20 2016-10-03 01:40:21 742325179 90820 wikitext 2009-12-03 33.0 0.001157
1148 329391659 179855 0 /* Modern business */ 1755816 Avaya1 2009-12-03 04:42:25 1 0 25985 329391543 ssbqhcq1a8tngsf1oows1lyfslobxh2 None None 179855 0 Rothschild_family 0 0 0 0.181589 2016-10-03 01:40:20 2016-10-03 01:40:21 742325179 90820 wikitext 2009-12-03 3.0 0.000509

As before we can aggregate all the information in these baby DFs into a user-level dataframe that summarizes different attributes.

# Define the aggregation function mappings to variables.
# We can apply multiple functions to the same column/series by nesting a second dictionary within
agg_dict_user = {'rev_id':{'revs_made':pd.Series.nunique},
                  'rev_timestamp':{'first_rev':np.min,'last_rev':np.max},
                  'rev_len_diff':{'rev_len_min':np.min,'rev_len_max':np.max,
                                  'rev_len_med':np.median,'rev_len_sum':np.sum},
                  'rev_timestamp_diff':{'rev_ts_min':np.min,'rev_ts_max':np.max,
                                        'rev_ts_avg':np.mean}
                 }

# Perform the aggregation
rev_agg_user = rev_gb_user.agg(agg_dict_user)

# Returns a multi-index column, simplify by dropping the top level
rev_agg_user.columns = rev_agg_user.columns.droplevel(0)

# Sort by number of revisions, and look at the first 5 rows
rev_agg_user.sort_values('revs_made',ascending=False).head()
revs_made rev_len_max rev_len_min rev_len_sum rev_len_med rev_ts_max rev_ts_min rev_ts_avg first_rev last_rev
rev_user_text
Avaya1 454 1294.0 -1284.0 11466.0 4.0 7.042164 0.000185 0.253996 2009-12-03 04:21:28 2016-03-21 01:32:10
86.26.0.25 400 3614.0 -453.0 21628.0 8.0 5.185579 0.000174 0.105351 2009-12-03 03:43:18 2010-03-04 16:46:53
82.26.0.138 266 2957.0 -1315.0 6433.0 6.0 16.947975 0.000231 0.389249 2010-07-29 02:05:42 2012-04-01 23:21:15
Mervyn 89 1376.0 -8712.0 -14770.0 -46.0 23.986134 0.004630 0.741456 2003-12-12 09:36:11 2016-09-08 07:45:33
ClueBot NG 66 92247.0 -11715.0 362795.0 -23.5 0.000174 0.000023 0.000085 2010-12-07 16:40:19 2016-08-10 13:18:39

Define some additional user-level statistics based on this aggregated data.

Tenure on article

# Compute tenure as difference between last and first revision, convert back to 1-day floats by dividing by timedelta64
rev_agg_user['tenure'] = (rev_agg_user['last_rev'] - rev_agg_user['first_rev'])/np.timedelta64(1,'D')

# Round values up to whole integers
rev_agg_user['tenure'] = rev_agg_user['tenure'].apply(np.ceil)

# Look at the longest-tenure editors
rev_agg_user['tenure'].sort_values(ascending=False).head()
rev_user_text
Mervyn          4654.0
Gabbe           4033.0
Tom harrison    3676.0
Topbanana       3538.0
Lessogg         3114.0
Name: tenure, dtype: float64
ax = rev_agg_user['tenure'].plot('hist',logy=True,bins=25)
ax.set_xlabel('Tenure (Days)')
ax.set_ylabel('Number of editors')
<matplotlib.text.Text at 0x7fbc613fa7f0>
logspace_bins = np.logspace(start=0, stop=4, num=25)
ax = rev_agg_user['tenure'].plot('hist',logy=True,logx=True,bins=logspace_bins)
ax.set_xlabel('Tenure (Days)')
ax.set_ylabel('Number of editors')
<matplotlib.text.Text at 0x7fbc613af9b0>
g = sb.lmplot(x='tenure',y='revs_made',data=rev_agg_user.query('tenure > 1'),aspect=1.5)
ax = g.axes[0][0]
ax.set_xlim((0,1e4))
ax.set_ylim((0,1e4))
ax.set_xscale('symlog')
ax.set_yscale('symlog')

Get user info

Define a function get_user_info that takes a revision DataFrame containing a "rev_user" column/series. For all the users in the revision history, get their user information like regristration date and current edit count.

def get_user_info(rev_df,conn):
    if 'rev_user' in rev_df.columns:
        
        # Get all the user IDs from the revision DF
        _ids = rev_df['rev_user'].unique().tolist() 
        
        # Remove the 0s and convert the rest to strings
        _ids = [str(i) for i in _ids if i != 0]
        
        # Join the list of strings into a big comma-separated string
        user_string = ', '.join(_ids)
        
        # Write the query
        ## Select specific columns
        ## from the user table
        ## where the user_ids are among the users revising the article
        s = """
                SELECT 
                    user_id, user_name, user_registration, user_editcount
                FROM 
                    user
                WHERE
                    user_id IN ({0})
                ORDER BY
                    user_editcount DESC
            """.format(user_string)

        # Run the query
        _df = pd.read_sql_query(s,conn)
        
        # Some of the results have a "bytestring" format
        byte_columns = ['user_name','user_registration']
    
        # For each column, convert it from bytestring to a utf8 string
        for col in byte_columns:
            _df[col] = _df[col].str.decode('utf8')

        # Some of the values are missing, recode them as Jan 1, 2000
        _df['user_registration'] = _df['user_registration'].replace({None:'20000101000000'})
        
        # Convert timestamps to datetimes
        _df['user_registration'] = _df['user_registration'].apply(lambda x:pd.datetime.strptime(x,'%Y%m%d%H%M%S'))
        
        # Return the results
        return _df

Run the get_user_info function on the "rev_df" DataFrame to get information about each of the users who contributed to the article.

# Refresh the database connection since too much time has passed since the last query
conn.ping()
conn.cursor().execute('use enwiki_p');

# Get the user information.
rev_user_info_df = get_user_info(rev_df,conn)
rev_user_info_df.head()
user_id user_name user_registration user_editcount
0 1215485 Cydebot 2006-04-07 01:24:50 5350171
1 7328338 Yobot 2008-06-17 22:33:17 4561195
2 13286072 ClueBot NG 2010-10-20 17:01:19 4105646
3 433328 SmackBot 2005-09-13 22:47:59 3734324
4 6569922 Addbot 2008-03-01 21:58:03 2838809

Merge the "rev_agg_user" and the "rev_user_info_df" DataFrames together by joining on the user name.

# Merge the two DataFrames together using the index of "reg_agg_user"
# and the "user_name" field from rev_user_info_df, joining on the left values which should be more inclusive
merged_rev_agg_user = pd.merge(rev_agg_user,rev_user_info_df,left_index=True,right_on='user_name',how='left')

# Check if the two DataFrames have the same number of users, if False then there will be NaNs
print(len(rev_agg_user) == len(rev_user_info_df))

# Show the first five rows
merged_rev_agg_user.head()
False
revs_made rev_len_max rev_len_min rev_len_sum rev_len_med rev_ts_max rev_ts_min rev_ts_avg first_rev last_rev tenure user_id user_name user_registration user_editcount
707 2 3.0 -3.0 0.0 0.0 15.689861 0.001042 7.845451 2014-06-24 17:13:28 2014-06-24 17:14:58 1.0 NaN 1.23.232.196 NaT NaN
707 1 40.0 40.0 40.0 40.0 7.854306 7.854306 7.854306 2013-08-05 21:31:17 2013-08-05 21:31:17 0.0 NaN 100.2.111.60 NaT NaN
707 3 114.0 41.0 251.0 96.0 2.032292 0.003148 0.681451 2015-06-12 15:44:24 2015-06-12 16:01:46 1.0 NaN 101.161.34.70 NaT NaN
707 1 -9.0 -9.0 -9.0 -9.0 3.385116 3.385116 3.385116 2016-06-12 01:05:06 2016-06-12 01:05:06 0.0 NaN 101.60.133.249 NaT NaN
707 1 134.0 134.0 134.0 134.0 0.010208 0.010208 0.010208 2014-06-25 04:22:02 2014-06-25 04:22:02 0.0 NaN 103.26.74.2 NaT NaN

What fraction of the user's toital edits are devoted to this single article?

merged_rev_agg_user['rev_fraction'] = merged_rev_agg_user['revs_made']/merged_rev_agg_user['user_editcount']

# Plot the distribution. Use log-bins since the data is so skewed
logspace_bins = np.logspace(start=-7, stop=0, num=25)
ax = merged_rev_agg_user['rev_fraction'].plot('hist',logy=False,logx=True,bins=logspace_bins)
ax.set_xlabel('Fraction of total edits')
ax.set_ylabel('Count')
<matplotlib.text.Text at 0x7fbc627a3cf8>

How long after a user's account registration did they make their first edit to this article?

merged_rev_agg_user['first_rev_account_age'] = merged_rev_agg_user['first_rev'] - merged_rev_agg_user['user_registration']
merged_rev_agg_user['first_rev_account_age'] = merged_rev_agg_user['first_rev_account_age']/np.timedelta64(1,'D')

# Plot the distribution. Use log-bins since the data is so skewed
logspace_bins = np.logspace(start=-1, stop=4, num=25)
ax = merged_rev_agg_user['first_rev_account_age'].plot('hist',logy=False,logx=True,bins=logspace_bins)
ax.set_xlabel('Account age at first article revision')
ax.set_ylabel('Count')
<matplotlib.text.Text at 0x7fbc65f4e438>

Do users editing the article earlier in their career end up contributing more to the article?

g = sb.lmplot(x='first_rev_account_age',y='revs_made',data=merged_rev_agg_user.query('tenure > 1'),aspect=1.5)
ax = g.axes[0][0]
ax.set_xlim((0,1e4))
ax.set_ylim((0,1e4))
ax.set_xscale('symlog')
ax.set_yscale('symlog')
ax.set_xlabel('Account age at first article revision')
ax.set_ylabel('Total article revisions')
<matplotlib.text.Text at 0x7fbc65fbac18>

Compare two articles

# Refresh the database connection since too much time has passed since the last query
conn.ping()
conn.cursor().execute('use enwiki_p');

# Get the second set of revisions
rev2_df = get_page_revisions('John D. Rockefeller',0,conn)

Do the data cleanup and feature engineering for later steps. Define a function to do all the feature engineering steps with one call.

def data_cleanup(rev_df):
    # Compute the rev_date from the timestamps
    rev_df['rev_date'] = rev_df['rev_timestamp'].apply(lambda x:x.date())

    # Set the revision lengths for the null rows to be the previous value
    rev_df['rev_len'] = rev_df['rev_len'].fillna(method='ffill')

    # Compute the diffs and store as a new series 
    rev_df['rev_len_diff'] = rev_df['rev_len'].diff()

    # Set the value for the first rev_len_diff to be the size of the rev_len
    rev_df.loc[0,'rev_len_diff'] = rev_df.loc[0,'rev_len']

    # Compute the diffs and store as a new series
    rev_df['rev_timestamp_diff'] = rev_df['rev_timestamp'].diff()

    # Convert the values of the new series to floats by dividing by 1 day time delta.
    rev_df['rev_timestamp_diff'] = rev_df['rev_timestamp_diff'].apply(lambda x:x/np.timedelta64(1,'D'))
    
    return rev_df

Run the cleanup on rev2_df and confirm it has all the variables (columns) we need.

rev2_df = data_cleanup(rev2_df)
rev2_df.head()
rev_id rev_page rev_text_id rev_comment rev_user rev_user_text rev_timestamp rev_minor_edit rev_deleted rev_len rev_parent_id rev_sha1 rev_content_model rev_content_format page_id page_namespace page_title page_restrictions page_counter page_is_redirect page_is_new page_random page_touched page_links_updated page_latest page_len page_content_model rev_date rev_len_diff rev_timestamp_diff
0 690097 186300 0 6280 Dave Farquhar 2003-02-21 21:17:33 0 0 2484 0 ixpdrnp04vzh1krj1jf8srmad29rpjb None None 186300 0 John_D._Rockefeller 0 0 0 0.434629 2016-10-02 19:20:43 2016-10-02 19:20:44 742274200 79088 wikitext 2003-02-21 2484.0 NaN
1 690115 186300 0 added link to The History of Standard Oil 6280 Dave Farquhar 2003-02-21 23:52:48 0 0 2634 690097 4fggz9g0eori9ddpa4cccjoh1ycfon7 None None 186300 0 John_D._Rockefeller 0 0 0 0.434629 2016-10-02 19:20:43 2016-10-02 19:20:44 742274200 79088 wikitext 2003-02-21 150.0 0.107813
2 719519 186300 0 added picture 6280 Dave Farquhar 2003-02-21 23:58:29 1 0 2797 690115 fd70cmcqp0wmf4b5kiwtr21a6wlzc2d None None 186300 0 John_D._Rockefeller 0 0 0 0.434629 2016-10-02 19:20:43 2016-10-02 19:20:44 742274200 79088 wikitext 2003-02-21 163.0 0.003947
3 897736 186300 0 On [[March 3]], [[1910]] Rockefeller announced... 62 Mav 2003-03-04 07:24:19 1 0 2971 719519 18594j1a9jsp5f6bxtqjdxea5bugl2y None None 186300 0 John_D._Rockefeller 0 0 0 0.434629 2016-10-02 19:20:43 2016-10-02 19:20:44 742274200 79088 wikitext 2003-03-04 174.0 10.309606
4 898751 186300 0 Added that John D. Rockerduck is named after him 0 212.205.2.92 2003-05-07 08:58:06 0 0 3076 897736 nqjlzy931g1oxvnpmh82rjuuxp1v8za None None 186300 0 John_D._Rockefeller 0 0 0 0.434629 2016-10-02 19:20:43 2016-10-02 19:20:44 742274200 79088 wikitext 2003-05-07 105.0 64.065127

Group by the "rev_date", compute the daily_revs, re-index to make the time continuous.

rev2_gb_date = rev2_df.groupby(['rev_date'])

daily_revs2 = rev2_gb_date.agg({'rev_id':pd.Series.nunique})

# Compute the first and last days revisions were observed
_min, _max = daily_revs2.index.min(), daily_revs2.index.max()

# Create a new index that is continuous over the whoel date range
_ix = pd.date_range(_min,_max)

# Reindex the daily revisions over the continuous date range filling in the blanks with 0s
daily_revs2_reindexed = daily_revs2.reindex(_ix).fillna(0)

Combine both of the daily_revs series into a DataFrame by merging, renaming the columns, and filling the blank values with 0s.

daily_revs_compared_df = pd.merge(daily_revs_reindexed,daily_revs2_reindexed,
                                  how='outer',left_index=True,right_index=True)

# The left DF was Mitt Romney and the right DF was John McCain. Rename to that effect
daily_revs_compared_df = daily_revs_compared_df.rename(columns={'rev_id_x':'Rothschild family','rev_id_y':'John D. Rockefeller'})

# Fill the null values with 0s
daily_revs_compared_df.fillna(0,inplace=True)

# Look at the first 5 rows
daily_revs_compared_df.head()
Rothschild family John D. Rockefeller
2003-02-06 2.0 0.0
2003-02-07 0.0 0.0
2003-02-08 0.0 0.0
2003-02-09 0.0 0.0
2003-02-10 0.0 0.0

Plot the comparisong of both results in a single chart. Use a rolling average of 60 days to smooth out noise.

ax = daily_revs_compared_df.rolling(60).mean().plot(lw=3)

# Label the axes
ax.set_xlabel('Date')
ax.set_ylabel('Revisions')
<matplotlib.text.Text at 0x7fbc60bfa400>