How has the Average Major League Baseball player Height and Weight Changed over time?


In order to determine how the Average Height and Weight of major league baseball players has changed over time, we look at Historical Baseball Data available on the Internet. The specific source of data chosen here is a database of baseball statistics over the years 1870 to 2016. http://www.seanlahman.com/baseball-database.html

This database has 27 tables. However to obtain the answer for our query above, we need to cross reference data from 2 tables in this database. The Master.csv table lists every player that has played the game from 1870 to 2016, along with their year of birth . Its schema is listed below.

Table 1: Master Table Schema

Field Description
playerID A unique code asssigned to each player
birthYear Year player was born
birthMonth Month player was born
birthDay Day player was born
birthCount Country where player was born
birthState State where player was born
birthCity City where player was born
deathYear Year player died
deathMonth Month player died
deathDay Day player died
deathCount Country where player died
deathState State where player died
deathCity City where player died
nameFirst Player's first name
nameLast Player's last name
nameGiven Player's given name
weight Player's weight in pounds
height Player's height in inches
bats Player's batting hand (left, right)
throws Player's throwing hand (left or right)
debut Date that player made first appearance
finalGame Date that player made last appearance
retroID ID used by retrosheet
bbrefID ID used by Baseball Reference website

The Batting.csv table lists the batting statistics for every player, for every year that he played the game of baseball between 1870 and 2016. Its schema is listed below

Table 2 Fielding Table schema

Field Description
playerID A unique code asssigned to each player
yearID Year
stint players stint
teamID Team
lgID League
Pos Position
G Games
GS Games Started
InnOuts Time Played (As Outs)
PO PutOuts
A Assists
E Errors
DP Double Plays
PB Passed Balls (Catcher)
WP Wild Pitches (Catcher)
SB Opponent Stolen Bases
CS Opponent Caught Stealing
ZR Zone Rating

We Utilize Apache Spark to perform the required database operations to answer our questions. The Code below explains the process of answering these questions, and shows how easy it is to use Spark to analyze Big Data. The Code to implement this query is implemented in Python, and can either be run on a local server or a cluster of servers. The example below was run on an Amazon EC2 Free Tier Ubuntu Server instance. The EC2 instance was set up with Python (Anaconda 3-4.1.1), Java, Scala, py4j, Spark and Hadoop. The code was written and executed in a Jupyter Notebook. Several guides are available on the internet describing how to install and run spark on an EC2 instance. One that particularly covers all these facets is https://medium.com/@josemarcialportilla/getting-spark-python-and-jupyter-notebook-running-on-amazon-ec2-dec599e1c297

Pyspark Libraries

Import the pyspark libraries to allow python to interact with spark. A description of the basic functionality of each of these libaries is provided in the code comments below. A more detailed explanation of the functionality of each of these libraries can be found in Apache's documentation on Spark https://spark.apache.org/docs/latest/api/python/index.html

In [51]:
# Import SparkContext. This is the main entry point for Spark functionality
# Import Sparkconf. We use Spark Conf to easily change the configuration settings when changing between local mode cluster mode. 
# Import SQLContext from pyspark.sql. We use the libraries here to read in data in csv format. The format of our native database
# Import count, avg, round from pyspark.sql.functions. This is used for the math operations needed to answer our questions
# Import Window from pyspark.sql to allow us to effectively partition and analyze data

from pyspark import SparkContext, SparkConf
from pyspark.sql import SQLContext
from pyspark.sql.functions import count
from pyspark.sql.functions import avg
from pyspark.sql.functions import round
from pyspark.sql.functions import cume_dist


from pyspark.sql.window import Window

Pyspark Configuration & Instantiation

We configure spark for local mode or cluster mode, configure our application name, and configure logging. Several other configuration settings can be programmed as well. A detailed explanation of these can be found at https://spark.apache.org/docs/latest/configuration.html

We pass the configuration to an instance of a SparkContext object, so that we can begin using Apache Spark

In [52]:
# The Master will need to change when running on a cluster. 
# If we need to specify multiple cores we can list something like local[2] for 2 cores, or local[*] to use all available cores. 
# All the available Configuration settings can be found at https://spark.apache.org/docs/latest/configuration.html

sc_conf = SparkConf().setMaster('local[*]').setAppName('Question5').set('spark.logConf', True)
In [53]:
# We instantiate a SparkContext object with the SparkConfig

sc = SparkContext(conf=sc_conf)

Pyspark CSV file Processing

We use the SQLContext library to easily allow us to read the csv files 'Salaries.csv' and 'Teams.csv'. These files are currently stored in Amazon s3 storage (s3://cs498ccafinalproject/) and are publicly available for download. They were copied over to a local EC2 instance by using the AWS command line interace command

aws s3 cp s3://cs498ccafinalproject . --recursive

In [54]:
# We create a sql context object, so that we can read in csv files easily, and create a data frame
sqlContext = SQLContext(sc)

masterData = sqlContext.read.format('com.databricks.spark.csv').options(header='true', inferschema='true').load('Master.csv')
fieldingData = sqlContext.read.format('com.databricks.spark.csv').options(header='true', inferschema='true').load('Fielding.csv')

Pyspark Data Operations.

In order to determine the average height and weight of major league baseball players over time, we perform the following operations in Spark

1) We clean the Master table to remove any entries that have null data for weight or height

2) We perform a join between the Master tabel and the Fielding table, so that we can later group players by the year they played

3) We query the joined table to return the average weight and average height for all players, grouped by year.

4) We sort the final table by year

The data shows that the average height has steadily increased from 5 foot 8, to 6 foot 1, between the years 1870 and 2016. The Average Weight has increased from roughly 156 lbs to 208 lbs. After staying fairly steady between 175 and 185 lbs from 1930 to 1985, the Average Weight has increased by roughly 20 lbs in the last 30 years.

In [55]:
# Clean out null entries 

masterData = masterData.na.drop(subset=["height"])
masterData = masterData.na.drop(subset=["weight"])

# Merge the two data frames
fieldingData = fieldingData.join(masterData, masterData.playerID == fieldingData.playerID, 'inner')


# Query the median weight and height for players by year
fieldingData.createOrReplaceTempView('questionData')

# Generate our query
sqlDF = sqlContext.sql('select yearID, avg(weight) as weight, avg(height) as height from questionData group by yearID order by yearID asc')

# Display results
sqlDF.show()

         
+------+------------------+-----------------+
|yearID|            weight|           height|
+------+------------------+-----------------+
|  1871|158.43349753694582| 68.5911330049261|
|  1872|158.08597285067873|68.33484162895928|
|  1873|160.24352331606218|68.42487046632124|
|  1874|160.14492753623188|68.59903381642512|
|  1875| 161.3641456582633| 68.6610644257703|
|  1876|162.43720930232558|68.95348837209302|
|  1877|165.42767295597486|69.12578616352201|
|  1878|169.40833333333333|           68.825|
|  1879|168.92342342342343|69.12162162162163|
|  1880| 168.1275720164609|69.11934156378601|
|  1881|171.54655870445345|69.17004048582996|
|  1882|170.83682983682985|69.25641025641026|
|  1883|172.54240631163708| 69.3767258382643|
|  1884|169.11282467532467|69.35957792207792|
|  1885|170.55612244897958|69.28401360544218|
|  1886|170.18210361067503|69.30298273155417|
|  1887|            170.24|            69.44|
|  1888|          171.3625|        69.690625|
|  1889|171.49417637271213|69.71547420965058|
|  1890| 169.7391304347826|69.81230116648993|
+------+------------------+-----------------+
only showing top 20 rows

Pyspark Test Results

We convert our spark data frames to pandas data frames, so it is easy to save them in a human readable csv format. These files contain the answers to the questions we posed.

In [56]:
# Examples to show how to print the results to an output file


pandas_sqlDF = sqlDF.toPandas()
pandas_sqlDF.to_csv('spark_question5_Player_Avg_Weight_Height_Over_Time.csv')
In [57]:
sc.stop()