Calculate batting average for each innings

Cricket is one of the most popular sports in the world, with a rich history dating back hundreds of years. As the sport has evolved, so too has our ability to collect and analyze cricket data. In the modern era, nearly every ball bowled in professional cricket is tracked and recorded, giving analysts access to a wealth of information on player and team performance.

Python has emerged as the go-to programming language for data analysis, and it‘s a great fit for exploring cricket datasets as well. In this guide, we‘ll walk through the process of analyzing cricket data using Python, from finding datasets to building predictive models. Whether you‘re a seasoned data scientist or a casual fan looking to dive deeper into the numbers, this guide will give you the tools you need to unlock new insights from cricket data.

Finding and Loading Cricket Data

The first step in any data analysis project is getting your hands on some data. Fortunately, there are many great sources for cricket data out there. Some popular options include:

  • Cricsheet: A volunteer-run project that provides ball-by-ball data for international and some domestic professional matches
  • ESPNcricinfo Statsguru: Comprehensive stats database that allows you to filter and download player and team data
  • Cricmetric: Scraped ball-by-ball data from ESPN Cricinfo dating back to 2001

For this guide, we‘ll use a dataset of all One Day International (ODI) matches played by legendary Indian batsman Sachin Tendulkar, downloaded from the Cricinfo Statsguru tool. You can download the CSV file here.

With our dataset in hand, we can load it into Python using the pandas library:

import pandas as pd

tendulkar_odi = pd.read_csv(‘tendulkar_odi.csv‘)

Let‘s take a quick look at the data:

tendulkar_odi.head()

This shows us the first five rows of the DataFrame, with columns like Runs, BF (balls faced), SR (strike rate), and more. We can already start to get a sense of Tendulkar‘s incredible ODI career, with big scores against all types of opposition.

Data Cleaning and Preparation

Real-world data is often messy, and our cricket dataset is no exception. We‘ll need to do some cleaning and preparation before we can start analyzing. A few key steps:

  1. Handle missing data: Rows with missing values for key columns like Runs can skew our analysis. We‘ll drop any rows with missing data for now.

    tendulkar_odi = tendulkar_odi.dropna(subset=[‘Runs‘])
  2. Convert columns to appropriate data types: The Runs, BF, 4s, and 6s columns are currently stored as strings, but we want to treat them as integers. We can convert them using astype():

    convert_dict = {‘Runs‘: int, ‘BF‘: int, ‘4s‘: int, ‘6s‘: int} 
    tendulkar_odi = tendulkar_odi.astype(convert_dict)
  3. Add some additional columns: To enable some interesting analysis, let‘s add a few more columns to our DataFrame.

    
    # Indicate whether Tendulkar was not out in each innings
    tendulkar_odi[‘not_out‘] = tendulkar_odi[‘Dismissal‘].apply(
     lambda d: 1 if d == ‘not out‘ else 0
    )

tendulkar_odi[‘Avg‘] = tendulkar_odi[‘Runs‘] / (tendulkar_odi[‘Inns‘] – tendulkar_odi[‘not_out‘])

tendulkar_odi[‘Year‘] = pd.to_datetime(tendulkar_odi[‘Start Date‘]).dt.year


With our data cleaned up and enhanced, we‘re ready to start exploring.

<h2>Exploratory Analysis and Visualization</h2>

Now comes the fun part - slicing and dicing our data to surface interesting insights. Let‘s start by looking at some high-level metrics for Tendulkar‘s career:

```python
print(f"Debut: {tendulkar_odi[‘Start Date‘].min()}")  
print(f"Last Match: {tendulkar_odi[‘Start Date‘].max()}")
print(f"Innings: {len(tendulkar_odi)}")   
print(f"Not Outs: {tendulkar_odi[‘not_out‘].sum()}")
print(f"Runs: {tendulkar_odi[‘Runs‘].sum()}")
print(f"Average: {tendulkar_odi[‘Avg‘].mean():.2f}")
print(f"Strike Rate: {tendulkar_odi[‘SR‘].mean():.2f}")
print(f"100s: {len(tendulkar_odi[tendulkar_odi[‘Runs‘] >= 100])}")  
print(f"50s: {len(tendulkar_odi[(tendulkar_odi[‘Runs‘] >= 50) & (tendulkar_odi[‘Runs‘] < 100)])}")

This gives us an amazing snapshot of Tendulkar‘s ODI accomplishments. Over a 24-year career, he played in 452 matches, scored over 18,000 runs at an average north of 44. He also scored 49 centuries and 96 half-centuries – truly mind-boggling numbers.

We can visualize some of these metrics as well. Let‘s look at how Tendulkar‘s runs tally grew over time:

import matplotlib.pyplot as plt

tendulkar_odi[‘Cumulative Runs‘] = tendulkar_odi[‘Runs‘].cumsum()

fig, ax = plt.subplots()
ax.plot(tendulkar_odi[‘Start Date‘], tendulkar_odi[‘Cumulative Runs‘])
ax.set_xlabel(‘Date‘) 
ax.set_ylabel(‘Runs‘)
ax.set_title("Sachin Tendulkar‘s Cumulative ODI Runs")

plt.show()

This graph shows Tendulkar‘s relentless run-scoring ability. He was able to maintain a remarkably steady scoring rate across his entire career.

We might also be curious to see how Tendulkar performed against different opposition teams. We can visualize his batting average against each team he faced:

fig, ax = plt.subplots(figsize=(10, 5))
tendulkar_odi.groupby([‘Opposition‘])[‘Avg‘].mean().plot.bar(ax=ax)  
ax.set_xlabel(‘Opposition‘)
ax.set_ylabel(‘Average‘)  
plt.xticks(rotation=30)
plt.show()

The graph shows that Tendulkar feasted on some opponents, averaging over 50 against teams like Australia, New Zealand, and West Indies. His average against the best teams is a testament to his greatness.

Predictive Modeling

While exploratory analysis helps uncover insights from past data, predictive modeling techniques let us forecast future match and player performances. Let‘s see if we can predict Tendulkar‘s runs total based on a few different input features.

We‘ll use the scikit-learn library to build a simple linear regression model:

from sklearn.model_selection import train_test_split  
from sklearn.linear_model import LinearRegression
from sklearn.metrics import r2_score

model_df = tendulkar_odi[[‘Runs‘, ‘BF‘, ‘4s‘, ‘6s‘, ‘Pos‘]].copy()
model_df = model_df.dropna()

X = model_df[[‘BF‘, ‘4s‘, ‘6s‘, ‘Pos‘]]  
y = model_df[[‘Runs‘]]

X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2)

lr = LinearRegression()  
lr.fit(X_train, y_train)

y_pred = lr.predict(X_test)  

print(f"R-squared: {r2_score(y_test, y_pred):.3f}")  
print(f"Coefficients: {lr.coef_}")

The model achieves an R-squared value of 0.886, indicating that it can predict Tendulkar‘s runs total reasonably well based on his balls faced, boundaries hit, and batting position. The model coefficients give the estimated impact of each input feature.

Of course, this is a very basic model. With more advanced techniques like regularization, feature selection, and hyperparameter tuning, we could develop more accurate and insightful models to predict player performance, match outcomes, and more.

Conclusion

This guide has only scratched the surface of what‘s possible when analyzing cricket data with Python. With the vast amount of data available and the powerful data wrangling, visualization, and machine learning tools in Python, the possibilities for extracting new insights are nearly limitless.

Whether you want to evaluate player and team performance, model match outcomes, or discover hidden trends in the data, Python is up to the task. Using the techniques outlined here, you now have the foundation to take your cricket analysis to the next level.

However, it‘s important to approach sports data analysis with a healthy dose of caution. On-field performance involves an incredible amount of luck, and focusing solely on the numbers will never give you the complete picture. The data should complement, not replace, the eye test and our intuitive appreciation for the subtleties of the game.

That said, it‘s an exciting time for quantitative analysis in cricket. With more matches being played and tracked than ever before, the data will only get richer. Aspiring analysts can hone their skills with the wealth of resources available online, including:

It will be fascinating to see how data analysis reshapes our understanding of cricket in the years to come. In the meantime, we can all appreciate the numbers behind the epic feats we see on the field – and Python gives us the power to discover those numbers for ourselves.

How useful was this post?

Click on a star to rate it!

Average rating 0 / 5. Vote count: 0

No votes so far! Be the first to rate this post.

Similar Posts