Posts Tagged With: Renaming Columns

Visualizing Baseball Pitching: Loading and Wrangling PitchLogic Data using Python

In my hobbies, I’ve always used my technical skills to support the endeavor. Web pages for the Boy Scout Troop, an online database for the school painting & landscaping projects, spreadsheets to manage the baseball rosters, radar to measure throwing speed, and email to keep everyone in the loop. So, it will come as no surprise to anyone I’ve encountered in those that I’m taking data visualization into my baseball coaching. This also gives me a chance to break down the process here and provide an opportunity for others to learn from and extend the code. This is part of a series of posts, with snippets delivered in manageable chunks.

Learning on DataCamp

As I was looking around for ways to learn AI and to learn Python as a way to access it, I found DataCamp. It’s a great site for learning Data and AI. There are a variety of career tracks (Data Analyst, Data Engineer, and Data Science, among others) and you can sample without paying. Each course in a track is also broken down into individual lessons, which are just a few minutes long. This allows you to learn in digestible chunks. It also will re-cap your progress when you reopen a course that you’ve already started.

You also get 3 workbooks on the DataLab that practice with data from files, Oracle, and SQL among others. You can use Python or R to manipulate it or ask the AI to do something (or start something for you). I was initially only using it for the exercises, then started playing with my baseball pitching files.

It’s usually $330 a year, but sometimes can be secured at a discount for one person or for a team (mine was half off). Well worth your money!

Basics

My PitchLogic baseball records a lot of information about every pitch, examining the pitcher’s delivery, the release, and the movement of the ball as it travels to the plate. The ball is identical to a Major League baseball in weight and covering, but instead of cork in the center, there are electronics. This means that we never hit the ball, just throw it.

You can export the data from the app, getting a CSV file via email with all the pitch data for the selected date range. I was always opening this in Excel and manipulating it to try to see patterns and to learn what “good” numbers were for age groups and individual pitchers. I had all kinds of formulas for highlighting cells that looked like “good” numbers. With the data being in Excel, I could have created some charts to better understand the data, but it was time-consuming and I wouldn’t know where I’d find value until I put in the work.

I started using ChatGPT to create some charts based on the data in the same way it was done in the app and in session reports on the web. I was including data from all sessions, so it was a little different. I also looked at data from a few seasons ago, which had long left my app but was stored in spreadsheets.

ChatGPT lets you look at the Python it creates to do what you want it to do. So, I started modifying that and reusing it for different players. Somehow, I found DataCamp and then started using DataLab to examine my data in more detail and practice the Python that I was learning.

When I imported the data, I realized that I could use my newly acquired skills and wrangle the data a little. When I was doing all my analysis in Excel, I had some formulas to create new column values, but I did a lot of copying and pasting. By using Python, I can easily apply those to any spreadsheet I drop in.

First, I just wanted to create a Player Name field so I didn’t have to spend time checking both first and last name. Then I wanted to parse my Memo column to separate out location and intended pitch type.

import pandas as pd

# Load the CSV file into a DataFrame
pitchLogic = pd.read_csv('PitchLogic.csv',parse_dates=["Date"])

# Combine names to Player Name
pitchLogic['Player Name'] = pitchLogic['First Name'] + ' ' + pitchLogic['Last Name']
# Split the memo field between location and intended pitch type
pitchLogic['Location'] = pitchLogic['Memo'].str[:1]
pitchLogic['Intended Type'] = pitchLogic['Memo'].str[2:4]

The Arm Slot value is the angle on a clock face for the pitcher’s arm as he’s throwing. The Spin Direction is the same for the direction in which the ball is spinning. An arm slot of 1:30 would be throwing with your arm at a 45 degree angle to your torso. A spin direction of 12:00 would be a ball spinning forward perpendicular to the ground. I want to compute the difference between these two as a way of evaluating the pitch. For a fastball, you usually want them as closely aligned as possible. For accuracy, you want them to be the same every time you throw a fastball, so that it’s predictable.

Computing the difference between the Arm Slot and Spin Direction is only easy when you’re doing it manually. If you do it in Excel or HCL Notes, it can be a rather complex formula. In Python, it’s not bad at all once you convert it to a time.

from datetime import datetime

# Skip rows that are missing Arm Slot or Spin Dir
pitchLogic = pitchLogic.dropna(subset=['Arm Slot', 'Spin Dir'])

# Convert 'Arm Slot' and 'Spin Dir' to datetime objects
pitchLogic['Arm Slot'] = pd.to_datetime(pitchLogic['Arm Slot'], format='%H:%M')
pitchLogic['Spin Dir'] = pd.to_datetime(pitchLogic['Spin Dir'], format='%H:%M')

# Compute the slot difference in minutes
pitchLogic['Slot Diff'] = (pitchLogic['Arm Slot'] - pitchLogic['Spin Dir']).dt.total_seconds() / 60

# Adjust the slot difference if it is less than -360
pitchLogic.loc[pitchLogic['Slot Diff'] < -360, 'Slot Diff'] += 720

# Convert the slot difference to integer
pitchLogic['Slot Diff'] = pitchLogic['Slot Diff'].astype(int)

# Format 'Arm Slot' and 'Spin Dir' to display only time as HH:MM
pitchLogic['Arm Slot'] = pitchLogic['Arm Slot'].dt.strftime('%H:%M')
pitchLogic['Spin Dir'] = pitchLogic['Spin Dir'].dt.strftime('%H:%M')

There is some old data in my PitchLogic files, from before they had auto-tagging of pitch type. For simplicity, and since much of my old data was from very young pitchers who only have one pitch (fastball), I defaulted everything to FF (four-seam fastball). Many of the columns in the CSV export from PitchLogic have column names that have changed over time and may continue to change, so I have an example of how to rename one.

# Check if 'Type' column exists before trying to fill NaN values
if 'Type' in pitchLogic.columns:
pitchLogic['Type'] = pitchLogic['Type'].fillna('FF')
else:
pitchLogic['Type'] = 'FF'

# Rename the 'Speed (mph)' column to 'Speed'
pitchLogic.rename(columns={'Speed (mph)': 'Speed'}, inplace=True)

I enter pitch location data into the Memo field, and also include the pitch type that the player intended if that differs from the auto-tagging. It is very common for players under 12 to have pitch type differ on some pitches, but not others. For high school pitchers, they tend to stay in the same pitch type, but may think it’s something different. At one assessment, a very good HS pitcher was throwing sliders and cutters, thinking he was throwing curveballs and fastballs.

Summary

This should give a good idea of how to import and wrangle the PitchLogic data, or any data of your own, in order to prepare some visualizations. Keep an eye on this blog for other pieces in this series to help understand visualizations using Python.

This series includes:

Categories: Python, Visualizations | Tags: , , , , , , , , , , , | 4 Comments

Create a free website or blog at WordPress.com.