Freedom Sale
Independence Day Special — Unlock the AI Path 70% off our most popular AI course · Limited time offer
--Days
--Hrs
--Min
--Sec
Claim Your Discount
✦ Beginner ⏱ 35 min

🏏 Build a Cricket Stats Analyser with Pandas

🎯 What You'll Build

A data analysis tool that loads cricket batting data, calculates averages and strike rates, ranks players, and generates bar charts.

📋 What You'll Need

1

Create sample batting data

We build a representative dataset in code — no download needed.

import pandas as pd

data = {
    'Player':       ['V Kohli','R Sharma','K Williamson','S Smith','B Bairstow',
                     'J Root','D Warner','A Finch','T Dilshan','C Gayle'],
    'Matches':      [250, 230, 160, 180, 120, 310, 160, 140, 330, 290],
    'Innings':      [238, 218, 152, 174, 112, 298, 152, 135, 315, 278],
    'Runs':         [12169, 9825, 7173, 8540, 4650, 11326, 5881, 5401, 10290, 10480],
    'HighScore':    [183, 264, 251, 239, 167, 254, 335, 172, 193, 333],
    'NotOut':       [48, 17, 19, 29, 12, 22, 6, 9, 41, 32],
    'BallsFaced':   [14200, 11800, 8600, 10200, 5200, 17000, 7200, 6800, 13000, 13800],
    'Hundreds':     [43, 29, 24, 26, 12, 31, 18, 15, 22, 25],
    'Fifties':      [63, 44, 41, 36, 31, 56, 21, 29, 47, 54],
}

df = pd.DataFrame(data)
df.to_csv('batting_stats.csv', index=False)
print("Created batting_stats.csv with", len(df), "players")
print(df[['Player','Runs','Matches']].head())
2

Calculate batting averages and strike rates

Average = runs / dismissals. Strike Rate = (runs / balls faced) * 100.

df = pd.read_csv('batting_stats.csv')

df['Dismissals']   = df['Innings'] - df['NotOut']
df['Average']      = (df['Runs'] / df['Dismissals']).round(2)
df['Strike_Rate']  = ((df['Runs'] / df['BallsFaced']) * 100).round(2)
df['100_per_inns'] = (df['Hundreds'] / df['Innings'] * 100).round(2)

print(df[['Player','Runs','Average','Strike_Rate','Hundreds']].sort_values('Runs', ascending=False).to_string())
Player   Runs  Average  Strike_Rate  Hundreds
8    T Dilshan  10290    41.49        79.15        22
9     C Gayle   10480    42.61        75.94        25
6    V Kohli   12169    63.91        85.70        43
7    J Root    11326    42.86        66.62        31
...
3

Rank and visualise top performers

Create a composite performance score and plot the results.

import matplotlib.pyplot as plt

# Normalise to 0–1 and build a composite score
for col in ['Runs','Average','Strike_Rate']:
    df[col + '_norm'] = (df[col] - df[col].min()) / (df[col].max() - df[col].min())

df['Score'] = (df['Runs_norm'] * 0.4 + df['Average_norm'] * 0.4 + df['Strike_Rate_norm'] * 0.2)
df_ranked   = df.sort_values('Score', ascending=False)

# Bar chart: top 10 by composite score
fig, axes = plt.subplots(1, 2, figsize=(14, 5))

df_ranked.plot(kind='barh', x='Player', y='Score', ax=axes[0], color='#1e3a5f', legend=False)
axes[0].set_title('Overall Performance Score (top 10)')
axes[0].set_xlabel('Composite Score (0-1)')

df_ranked.plot(kind='barh', x='Player', y='Average', ax=axes[1], color='#22c55e', legend=False)
axes[1].set_title('Batting Average')
axes[1].set_xlabel('Average')

plt.tight_layout()
plt.savefig('cricket_stats.png', dpi=120)
plt.show()
4

Compare two players head-to-head

A function that prints a formatted comparison between any two players.

def head_to_head(p1_name, p2_name):
    p1 = df[df['Player'] == p1_name].iloc[0]
    p2 = df[df['Player'] == p2_name].iloc[0]

    print(f"\n{'Stat':<20} {p1_name:<18} {p2_name}")
    print("-" * 55)
    for stat in ['Runs','Average','Strike_Rate','Hundreds','Fifties']:
        val1 = p1[stat]; val2 = p2[stat]
        winner = '<-- better' if val1 > val2 else '    better -->' if val2 > val1 else '       tie'
        print(f"{stat:<20} {str(val1):<18} {val2}  {winner}")

head_to_head('V Kohli', 'R Sharma')
💡 Tip: The composite scoring formula weights Average and Runs equally (40% each) and Strike Rate less (20%) because raw runs reflect longevity while average reflects consistency. Adjust the weights to favour T20 specialists or Test specialists.

🎉 You Did It!

You turned raw CSV data into rankings and visualisations. The normalisation + composite score technique is used in everything from sports analytics to product comparison tools and investment screening.

Found something wrong?

Spotted a bug, broken code, or something that doesn't look right? Tell us what's off and we'll fix it.