NYC Data Science Academy| Blog
Bootcamps
Lifetime Job Support Available Financing Available
Bootcamps
Data Science with Machine Learning Flagship ๐Ÿ† Data Analytics Bootcamp Artificial Intelligence Bootcamp New Release ๐ŸŽ‰
Free Lesson
Intro to Data Science New Release ๐ŸŽ‰
Find Inspiration
Find Alumni with Similar Background
Job Outlook
Occupational Outlook Graduate Outcomes Must See ๐Ÿ”ฅ
Alumni
Success Stories Testimonials Alumni Directory Alumni Exclusive Study Program
Courses
View Bundled Courses
Financing Available
Bootcamp Prep Popular ๐Ÿ”ฅ Data Science Mastery Data Science Launchpad with Python View AI Courses Generative AI for Everyone New ๐ŸŽ‰ Generative AI for Finance New ๐ŸŽ‰ Generative AI for Marketing New ๐ŸŽ‰
Bundle Up
Learn More and Save More
Combination of data science courses.
View Data Science Courses
Beginner
Introductory Python
Intermediate
Data Science Python: Data Analysis and Visualization Popular ๐Ÿ”ฅ Data Science R: Data Analysis and Visualization
Advanced
Data Science Python: Machine Learning Popular ๐Ÿ”ฅ Data Science R: Machine Learning Designing and Implementing Production MLOps New ๐ŸŽ‰ Natural Language Processing for Production (NLP) New ๐ŸŽ‰
Find Inspiration
Get Course Recommendation Must Try ๐Ÿ’Ž An Ultimate Guide to Become a Data Scientist
For Companies
For Companies
Corporate Offerings Hiring Partners Candidate Portfolio Hire Our Graduates
Students Work
Students Work
All Posts Capstone Data Visualization Machine Learning Python Projects R Projects
Tutorials
About
About
About Us Accreditation Contact Us Join Us FAQ Webinars Subscription An Ultimate Guide to
Become a Data Scientist
    Login
NYC Data Science Acedemy
Bootcamps
Courses
Students Work
About
Bootcamps
Bootcamps
Data Science with Machine Learning Flagship
Data Analytics Bootcamp
Artificial Intelligence Bootcamp New Release ๐ŸŽ‰
Free Lessons
Intro to Data Science New Release ๐ŸŽ‰
Find Inspiration
Find Alumni with Similar Background
Job Outlook
Occupational Outlook
Graduate Outcomes Must See ๐Ÿ”ฅ
Alumni
Success Stories
Testimonials
Alumni Directory
Alumni Exclusive Study Program
Courses
Bundles
financing available
View All Bundles
Bootcamp Prep
Data Science Mastery
Data Science Launchpad with Python NEW!
View AI Courses
Generative AI for Everyone
Generative AI for Finance
Generative AI for Marketing
View Data Science Courses
View All Professional Development Courses
Beginner
Introductory Python
Intermediate
Python: Data Analysis and Visualization
R: Data Analysis and Visualization
Advanced
Python: Machine Learning
R: Machine Learning
Designing and Implementing Production MLOps
Natural Language Processing for Production (NLP)
For Companies
Corporate Offerings
Hiring Partners
Candidate Portfolio
Hire Our Graduates
Students Work
All Posts
Capstone
Data Visualization
Machine Learning
Python Projects
R Projects
About
Accreditation
About Us
Contact Us
Join Us
FAQ
Webinars
Subscription
An Ultimate Guide to Become a Data Scientist
Tutorials
Data Analytics
  • Learn Pandas
  • Learn NumPy
  • Learn SciPy
  • Learn Matplotlib
Machine Learning
  • Boosting
  • Random Forest
  • Linear Regression
  • Decision Tree
  • PCA
Interview by Companies
  • JPMC
  • Google
  • Facebook
Artificial Intelligence
  • Learn Generative AI
  • Learn ChatGPT-3.5
  • Learn ChatGPT-4
  • Learn Google Bard
Coding
  • Learn Python
  • Learn SQL
  • Learn MySQL
  • Learn NoSQL
  • Learn PySpark
  • Learn PyTorch
Interview Questions
  • Python Hard
  • R Easy
  • R Hard
  • SQL Easy
  • SQL Hard
  • Python Easy
Data Science Blog > Student Works > NBA player statistics (Sumanth Reddy & Joseph Russo)

NBA player statistics (Sumanth Reddy & Joseph Russo)

Joseph Russo
Posted on Jul 24, 2015
The skills we demoed here can be learned through taking Data Science with Machine Learning bootcamp with NYC Data Science Academy.

Introduction

During the recent NBA playoffs, the Cleveland Cavaliers suffered multiple key injuries to some of their star players: Kevin Love and Kyrie Irving.

With a very top-heavy roster in terms of talent, this tasked Lebron James with the challenge of carrying the team. James is the best player in the NBA, and immediately saw a large uptick in traditional NBA counting statistics.

Despite this, we were curious if James' efficiency changed, as it seems logical to see an adverse effect when losing the presence of great teammates.

Before we could dive into the analysis, we had to scrape the data from NBA Reference, a website that stores all historical data concerning the NBA.

Using Python, one is able to access the underlying data inside the HTMLโ€™s Document Object Model (DOM) and eventually store this information as a comma-separated value (CSV) file.



 

Importing Libraries

A common first step is to load useful libraries, and in particular, for web-scraping the BeautifulSoup library is very handy.  In addition, Pandas and Seaborn libraries were imported for data analysis and visualization, respectively.

from bs4 import BeautifulSoup
import requests

import pandas as pd
import numpy as np

#import matplotlib.pyplot as plt
import seaborn as sns

#needed to convert unicode to numeric
import unicodedata

from IPython.display import Image

%pylab inline


 

Web-Scraping

Upon investigating the DOM, there are various tags in the tree structure, and in particular the "thead" and "tbody" elements had the information of interest.  The "trick" was to use these object's methods to form the rows and columns objects, which eventually are used to form a friendly Pandas dataframe object.

basketball_website_screenshot_HTML_DOM_example-1

#regular season data
leb = 'http://www.basketball-reference.com/players/j/jamesle01/gamelog/2015/'

#######
#lebron
#######
player_string_key = leb
req = requests.get(player_string_key)
text = BeautifulSoup(req.text, "html.parser")
stats = text.find('table', {'id': 'pgl_basic'})

# find the schema
cols = [i.get_text() for i in stats.thead.find_all('th')]  

# convert from unicode to string
cols = [x.encode('UTF8') for x in cols]                    

#these are schema with empty string names
cols[5]='home_away'
cols[7]='win-loss'

# get rows
rows = [i.get_text().split('n') for i in stats.tbody.find_all('tr')] 

# convert rows to strings
for i in range(len(rows)):
    rows[i] = [x.encode('UTF8') for x in rows[i]]                          

rows=rows[1:-1]

short = []

for i in range(len(rows)):
    if len(rows[i]) < 31:
        short.append(i)
        
new_rows = []

for i in range(len(rows)):
    if i in short:
        continue
    else:
        new_rows.append(rows[i])

l = range(len(new_rows))

######
#change df name for each player (lebron, love, etc....needs to part of automation for multi-player)
######
lebron = pd.DataFrame(columns=cols, index = l)    # create dataframe with schema

for i in l:
    try:
        # the split function was adding an empty string to the front and end of each row, needed to be removed
        new_rows[i]=new_rows[i][1:-1]  
    except ValueError:
        continue
for i in l:
    try:
        lebron.loc[i]=new_rows[i]
    except ValueError:
        continue


 

Data Clean Up

Once the HTML data was stored into a Pandas Dataframe object, a quick inspection shows that there are duplicate rows, columns with missing names, and that the numeric values are not actually numeric, but strings (which is much more difficult to analyze statistically).

#Note: raw scraped data is not numeric.

#since the entire schema is replicated every N rows, we can just check one of the columns for the match
validRow_boolVector = lebron['Rk'] != 'Rk'
validRow_boolVector = lebron['Rk'] != 'Rk' #and (lebron['MP'] != ('Did Not Play' or 'Inactive')))

#use the boolean vector as a mask for only keeping True values
lebron = lebron[validRow_boolVector]

#######

#2015-06-23
#Jason - head function returns a formatted string about to make it "pretty"
#saveHead = blah.head() isnt a good idea, as the head function is more for display, and not saving original data
#unicodedata.numeric(lebron.FG[:,])

#This will overwrite the dataframe itself with the converted object types....AVOID!
#lebron = lebron.convert_objects(convert_numeric=True).dtypes

#Convert "objects" in the dataframe to numeric, float, etc
lebron = lebron.convert_objects(convert_numeric=True)

#test that these columns are now actually numeric
#print lebron.FG[0] + 1

print lebron[1:25]


 

Data Validation

Once the data has been cleaned, it was checked against the CSV file provided  by the website.   When comparing the files, they looked very similar, and confirmed the values generated by the HTML web-scraping were accurate.

#load CSV from website
lebron_validate = pd.read_table('Lebron_CSV_validatedSetFromWebsite.txt', sep=',')

#rename empty schema with appropriate names
lebron_validate.rename(columns={'Unnamed: 5': 'home_away'}, inplace=True)
lebron_validate.rename(columns={'Unnamed: 7': 'win-loss'}, inplace=True)

#quick glance at validation set
#print lebron_validate[1:10]

##validate we got the dataframe
#print lebron_validate.head(10)

#since the entire schema is replicated every N rows, we can just check one of the columns for the match
validate_validRow_boolVector = lebron_validate['Rk'] != 'Rk' #and (lebron_validate['MP'] != ('Did Not Play' or 'Inactive')))
#validate_validRow_boolVector = (lebron_validate['Rk'] != 'Rk' and (lebron_validate['MP'] != ('Did Not Play' or 'Inactive')))


#use the boolean vector as a mask for only keeping True values
lebron_validate = lebron_validate[validate_validRow_boolVector]

##Are these numeric?
#print type(lebron_validate.STL[0])

#Convert "objects" in the dataframe to numeric, float, etc
lebron_validate = lebron_validate.convert_objects(convert_numeric=True)

##Check conversion
#print type(lebron_validate.STL[0])
#print lebron_validate.FG[0] + 1

#Change NaNs to empty string
#glancing at downloaded .txt file....the empty values between commas were replaced with NaN
#DESTROYING DF
#lebron_validate = lebron_validate.fillna(' ', inplace=True)
lebron_validate = lebron_validate.fillna('')

##validate NaNs are replaced with empty string
#print lebron_validate.head(10)

print lebron_validate.head(25)


 

Visualization using Seaborn

Each NBA player has specific key statistics that are useful to summarize their performance per game.  Seaborn allows a direct way to summarize and visualize these key statistics using a box-plot.

#set the SeaBorn plotting parameters
sns.set(context='talk', style='white', palette='deep', font='sans-serif', font_scale=2, rc=None)

#choose columns of lebron dataframe for plotting
plotColumns = ['PTS','AST','STL','BLK','FG','FGA','TRB','TOV']

#set the parent figure size
figsize(16,10)

#grab handle to boxPlot object
lebron_boxPlot = sns.boxplot(lebron[plotColumns])

#get axes child handle
lebron_boxPlot_axes = lebron_boxPlot.axes

#set the title
lebron_boxPlot_axes.set_title('Lebron: 2014-2015 - Regular Season')

#set the range to allow BLK feature to not be flush with bottom of boxPlot
lebron_boxPlot_axes.set_ylim(-10,50)
#another way
#sns.set_ylim

#set current axes labels
sns.axlabel("Features","Number")

 

LebronStatistics



 

Visualization in R

For a preliminary analysis, various box-plots were created using R to visualize the impact of the prescience of Cavalier teammate's on Lebron James's performance.

lebron_MP

As seen from this first boxplot, the data was not evenly distributed. Out of 20 play-off games, only three featured Lebron, Kevin, and Kyrie in the same lineup.

During the regular season however, all three players participated in almost 90% of the games together.  We felt this added a better baseline of consistent performance, and Lebron's average regular season statistics are represented by the blue line.

Even without considering teammates, Lebron clearly played a lot more minutes in the playoffs relative to the regular season.

That said, when both Kevin and Kyrie were hurt, Lebron played more minutes in every game than his averages from any other situation.

 

lebron_usage

The 2nd box-plot is easier to interpret: As star teammates get hurt, Lebron's usage exhibits large jumps.

Trying to gauge how often Lebron had the ball in his hands, we defined usage as the summation of shots attempted, assists, and turnovers.

This appears to support the hypothesis that NBA teams constantly funnel the ball through their star players.

 

lebron_FGperc

The final box-plot tested our main question: How did Lebron's efficiency change as his usage went up?

While the trend downwards is quite clear, it is worth noting that Kevin and Kyrie got hurt at different points in the playoffs, and the Cavaliers were facing tougher teams over the course of time.

While it would be natural to assume that Lebron's efficiency fell dramatically as his teammates got hurt, it is also possible that the increasing strength of his opponents was just as significant of a factor, if not more.



 

Conclusions 

  • The Python library BeautifulSoup allows a direct way to access the underlying HTML elements or โ€œscrapโ€ a web-page.
  • The Pandas and Seaborn libraries provide convenient storage, manipulation, and visualization of data.
  • When star NBA players get injured, their allotted minutes and usage are compensated for by the most prominent remaining player(s) on that team.
  • Box-plots have limitations when it comes to small sample sizes. It is difficult to reach conclusions about the distribution of your data without performing more intensive analysis.

Future Goals

  • Scrap the entire NBA for the last 10 years
  • Apply machine learning algorithms to prediction of future NBA championship playoffs

 

About Author

Joseph Russo

View all posts by Joseph Russo >

Leave a Comment

Cancel reply

You must be logged in to post a comment.

http://rubyslape.wordpress.com/2015/06/24/is-hammertoe-surgery-successful August 21, 2017
I'm not positive the place you are getting your information, but good topic. I needs to spend some time finding out more or figuring out more. Thank you for fantastic info I used to be in search of this information for my mission.
strider toddler bike February 16, 2016
With all the pleasing features, the pros obviously outweigh the cons of this product. But what if you have already co-signed for a car loan. If you also think the same and want your child to develop then educational toys is the answer to all your problems.
strider toddler bike February 9, 2016
First, Cobb worked patiently with Norman and taught him how to ride a scooter. Also, you need to set a schedule for exercise so that the biological clock of your body is set. Here's a way you can polish your long putting: First, don't go for an opening.
cheap kazam bike review February 9, 2016
Since, the cycle trainer is a qualified & experienced person having enough knowledge & experience to guide you through the right path. Dee Dee has been training at Florida Fitness Concepts since 1994. You should be able to make your own health potions, PP potions, and Pokeballs.

View Posts by Categories

All Posts 2399 posts
AI 7 posts
AI Agent 2 posts
AI-based hotel recommendation 1 posts
AIForGood 1 posts
Alumni 60 posts
Animated Maps 1 posts
APIs 41 posts
Artificial Intelligence 2 posts
Artificial Intelligence 2 posts
AWS 13 posts
Banking 1 posts
Big Data 50 posts
Branch Analysis 1 posts
Capstone 206 posts
Career Education 7 posts
CLIP 1 posts
Community 72 posts
Congestion Zone 1 posts
Content Recommendation 1 posts
Cosine SImilarity 1 posts
Data Analysis 5 posts
Data Engineering 1 posts
Data Engineering 3 posts
Data Science 7 posts
Data Science News and Sharing 73 posts
Data Visualization 324 posts
Events 5 posts
Featured 37 posts
Function calling 1 posts
FutureTech 1 posts
Generative AI 5 posts
Hadoop 13 posts
Image Classification 1 posts
Innovation 2 posts
Kmeans Cluster 1 posts
LLM 6 posts
Machine Learning 364 posts
Marketing 1 posts
Meetup 144 posts
MLOPs 1 posts
Model Deployment 1 posts
Nagamas69 1 posts
NLP 1 posts
OpenAI 5 posts
OpenNYC Data 1 posts
pySpark 1 posts
Python 16 posts
Python 458 posts
Python data analysis 4 posts
Python Shiny 2 posts
R 404 posts
R Data Analysis 1 posts
R Shiny 560 posts
R Visualization 445 posts
RAG 1 posts
RoBERTa 1 posts
semantic rearch 2 posts
Spark 17 posts
SQL 1 posts
Streamlit 2 posts
Student Works 1687 posts
Tableau 12 posts
TensorFlow 3 posts
Traffic 1 posts
User Preference Modeling 1 posts
Vector database 2 posts
Web Scraping 483 posts
wukong138 1 posts

Our Recent Popular Posts

AI 4 AI: ChatGPT Unifies My Blog Posts
by Vinod Chugani
Dec 18, 2022
Meet Your Machine Learning Mentors: Kyle Gallatin
by Vivian Zhang
Nov 4, 2020
NICU Admissions and CCHD: Predicting Based on Data Analysis
by Paul Lee, Aron Berke, Bee Kim, Bettina Meier and Ira Villar
Jan 7, 2020

View Posts by Tags

#python #trainwithnycdsa 2019 2020 Revenue 3-points agriculture air quality airbnb airline alcohol Alex Baransky algorithm alumni Alumni Interview Alumni Reviews Alumni Spotlight alumni story Alumnus ames dataset ames housing dataset apartment rent API Application artist aws bank loans beautiful soup Best Bootcamp Best Data Science 2019 Best Data Science Bootcamp Best Data Science Bootcamp 2020 Best Ranked Big Data Book Launch Book-Signing bootcamp Bootcamp Alumni Bootcamp Prep boston safety Bundles cake recipe California Cancer Research capstone car price Career Career Day ChatGPT citibike classic cars classpass clustering Coding Course Demo Course Report covid 19 credit credit card crime frequency crops D3.js data data analysis Data Analyst data analytics data for tripadvisor reviews data science Data Science Academy Data Science Bootcamp Data science jobs Data Science Reviews Data Scientist Data Scientist Jobs data visualization database Deep Learning Demo Day Discount disney dplyr drug data e-commerce economy employee employee burnout employer networking environment feature engineering Finance Financial Data Science fitness studio Flask flight delay football gbm Get Hired ggplot2 googleVis H20 Hadoop hallmark holiday movie happiness healthcare frauds higgs boson Hiring hiring partner events Hiring Partners hotels housing housing data housing predictions housing price hy-vee Income industry Industry Experts Injuries Instructor Blog Instructor Interview insurance italki Job Job Placement Jobs Jon Krohn JP Morgan Chase Kaggle Kickstarter las vegas airport lasso regression Lead Data Scienctist Lead Data Scientist leaflet league linear regression Logistic Regression machine learning Maps market matplotlib Medical Research Meet the team meetup methal health miami beach movie music Napoli NBA netflix Networking neural network Neural networks New Courses NHL nlp NYC NYC Data Science nyc data science academy NYC Open Data nyc property NYCDSA NYCDSA Alumni Online Online Bootcamp Online Training Open Data painter pandas Part-time performance phoenix pollutants Portfolio Development precision measurement prediction Prework Programming public safety PwC python Python Data Analysis python machine learning python scrapy python web scraping python webscraping Python Workshop R R Data Analysis R language R Programming R Shiny r studio R Visualization R Workshop R-bloggers random forest Ranking recommendation recommendation system regression Remote remote data science bootcamp Scrapy scrapy visualization seaborn seafood type Selenium sentiment analysis sentiment classification Shiny Shiny Dashboard Spark Special Special Summer Sports statistics streaming Student Interview Student Showcase SVM Switchup Tableau teachers team team performance TensorFlow Testimonial tf-idf Top Data Science Bootcamp Top manufacturing companies Transfers tweets twitter videos visualization wallstreet wallstreetbets web scraping Weekend Course What to expect whiskey whiskeyadvocate wildfire word cloud word2vec XGBoost yelp youtube trending ZORI

NYC Data Science Academy

NYC Data Science Academy teaches data science, trains companies and their employees to better profit from data, excels at big data project consulting, and connects trained Data Scientists to our industry.

NYC Data Science Academy is licensed by New York State Education Department.

Get detailed curriculum information about our
amazing bootcamp!

Please enter a valid email address
Sign up completed. Thank you!

Offerings

  • HOME
  • DATA SCIENCE BOOTCAMP
  • ONLINE DATA SCIENCE BOOTCAMP
  • Professional Development Courses
  • CORPORATE OFFERINGS
  • HIRING PARTNERS
  • About

  • About Us
  • Alumni
  • Blog
  • FAQ
  • Contact Us
  • Refund Policy
  • Join Us
  • SOCIAL MEDIA

    ยฉ 2025 NYC Data Science Academy
    All rights reserved. | Site Map
    Privacy Policy | Terms of Service
    Bootcamp Application