PRACTICAL 5: EXPLORATORY DATA ANALYSIS (EDA)

DATASET:
Match.csv

STEPS TO USE:
1. Keep Match.csv in the same folder from which you run Python, or change the file path in pd.read_csv().
2. Install required libraries using:
   python -m pip install pandas numpy seaborn matplotlib
3. Run the numerical summary code first, if required.
4. Copy and run each graph's code separately. Each graph code is independent; do not combine graph sections.
5. If running from IDLE, open a new editor window (File > New File), paste one graph code, save it, and press F5.
6. If a graph uses a column that is not in your Match.csv, check the column names using print(df.columns) and replace it with the matching column in your dataset.


NUMERICAL SUMMARY CODE:

import pandas as pd
import numpy as np

df = pd.read_csv("Match.csv")

num_cols = df.select_dtypes(include=[np.number]).columns

for col in num_cols:
    mean_val = df[col].mean()
    median_val = df[col].median()
    mode_val = df[col].mode().iloc[0] if not df[col].mode().empty else None
    skew_val = df[col].skew()
    kurtosis_val = df[col].kurtosis()

    print(f"Mean of {col}: {mean_val}")
    print(f"Median of {col}: {median_val}")
    print(f"Mode of {col}: {mode_val}")
    print(f"Skewness of {col}: {skew_val}")
    print(f"Kurtosis of {col}: {kurtosis_val}")

    if np.isclose(skew_val, 0, atol=0.1):
        print("Data is approximately symmetric")
    elif skew_val > 0:
        print("Data is positively skewed")
    else:
        print("Data is negatively skewed")
    print("-" * 60)


GRAPH 1: BAR PLOT - WINS AT TOP 10 VENUES

Use this code to display wins by team at the 10 most frequent venues.

CODE:

import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt

df = pd.read_csv("Match.csv")
venue_wins = df.groupby(["Venue_Name", "Match_Winner_Id"]).size().reset_index(name="Wins")
top_venues = df["Venue_Name"].value_counts().head(10).index
venue_wins = venue_wins[venue_wins["Venue_Name"].isin(top_venues)]

plt.figure(figsize=(14, 7))
sns.barplot(data=venue_wins, x="Venue_Name", y="Wins", hue="Match_Winner_Id")
plt.xticks(rotation=45, ha="right")
plt.title("Venue Advantage: Wins by Team at Top Venues")
plt.xlabel("Venue")
plt.ylabel("Number of Wins")
plt.tight_layout()
plt.show()


GRAPH 2: BAR PLOT - TOSS DECISION FREQUENCY

Use this code to display the frequency of toss decisions.

CODE:

import pandas as pd
import matplotlib.pyplot as plt

df = pd.read_csv("Match.csv")
toss_counts = df["Toss_Decision"].value_counts()

plt.figure(figsize=(6, 5))
toss_counts.plot(kind="bar", color=["skyblue", "orange"])
plt.title("Frequency of Toss Decisions")
plt.xlabel("Toss Decision")
plt.ylabel("Number of Matches")
plt.tight_layout()
plt.show()


GRAPH 3: PIE CHART - HOME GROUND WINS

This code assumes OpponentTeam name identifies the home team and Match_Winner_Id is the winner id. It maps team ids to names from the dataset.

CODE:

import pandas as pd
import matplotlib.pyplot as plt

df = pd.read_csv("Match.csv")

team_pairs = pd.concat([
    df[["Opponent_Team_Id", "OpponentTeam name"]].rename(
        columns={"Opponent_Team_Id": "Team_ID", "OpponentTeam name": "Team_Name"}),
    df[["Match_Winner_Id", "Team name"]].rename(
        columns={"Match_Winner_Id": "Team_ID", "Team name": "Team_Name"}),
    df[["Match_Winner_Id", "OpponentTeam name"]].rename(
        columns={"Match_Winner_Id": "Team_ID", "OpponentTeam name": "Team_Name"})
]).dropna().drop_duplicates()
team_map = team_pairs.groupby("Team_ID")["Team_Name"].first()
df["Match_Winner_Name"] = df["Match_Winner_Id"].map(team_map)

home_wins = df[df["OpponentTeam name"] == df["Match_Winner_Name"]]
home_win_counts = home_wins["OpponentTeam name"].value_counts()

plt.figure(figsize=(8, 8))
plt.pie(home_win_counts, labels=home_win_counts.index, autopct="%1.1f%%", startangle=90)
plt.title("Home Ground Wins by Team")
plt.axis("equal")
plt.show()


GRAPH 4: SCATTER PLOT - VENUE-WISE WINS

Use this code to display the number of wins for teams at the top 10 venues.

CODE:

import pandas as pd
import matplotlib.pyplot as plt

df = pd.read_csv("Match.csv")
venue_wins = df.groupby(["Venue_Name", "Match_Winner_Id"]).size().reset_index(name="Wins")
top_venues = df["Venue_Name"].value_counts().head(10).index
venue_wins = venue_wins[venue_wins["Venue_Name"].isin(top_venues)].copy()
venue_positions = {venue: i for i, venue in enumerate(top_venues)}
venue_wins["Venue_Pos"] = venue_wins["Venue_Name"].map(venue_positions)

plt.figure(figsize=(14, 7))
for team in venue_wins["Match_Winner_Id"].unique():
    team_data = venue_wins[venue_wins["Match_Winner_Id"] == team]
    plt.scatter(team_data["Venue_Pos"], team_data["Wins"], label=str(team), s=100)

plt.xticks(range(len(top_venues)), top_venues, rotation=45, ha="right")
plt.xlabel("Venue")
plt.ylabel("Number of Wins")
plt.title("Venue-wise Wins by Team (Scatter Plot)")
plt.legend(title="Match Winner ID", bbox_to_anchor=(1.02, 1), loc="upper left")
plt.tight_layout()
plt.show()


GRAPH 5: BOX PLOT - WINNING MARGIN BY TOSS DECISION

Use this code to compare the winning margin for each toss decision.

CODE:

import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt

df = pd.read_csv("Match.csv")
plt.figure(figsize=(8, 6))
sns.boxplot(data=df, x="Toss_Decision", y="Won_By")
plt.title("Winning Margin by Toss Decision")
plt.xlabel("Toss Decision")
plt.ylabel("Winning Margin")
plt.show()


GRAPH 6: LINE PLOT - FREQUENCY OF WIN TYPES

Use this code to display the frequency of each win type.

CODE:

import pandas as pd
import matplotlib.pyplot as plt

df = pd.read_csv("Match.csv")
win_counts = df["Win_Type"].value_counts().sort_index()

plt.figure(figsize=(8, 5))
plt.plot(win_counts.index.astype(str), win_counts.values, marker="o", linewidth=2)
plt.title("Frequency of Win Types")
plt.xlabel("Win Type")
plt.ylabel("Number of Matches")
plt.grid(True)
plt.tight_layout()
plt.show()


GRAPH 7: VIOLIN PLOT - WINNING MARGIN BY TOSS DECISION

Use this code to show the distribution of winning margins for each toss decision.

CODE:

import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt

df = pd.read_csv("Match.csv")
plt.figure(figsize=(8, 6))
sns.violinplot(data=df, x="Toss_Decision", y="Won_By", inner="quartile")
plt.title("Winning Margin by Toss Decision")
plt.xlabel("Toss Decision")
plt.ylabel("Winning Margin")
plt.show()


GRAPH 8: SWARM PLOT - MATCH WINNER BY TOSS DECISION

Use this code to display individual winner ids for each toss decision.

CODE:

import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt

df = pd.read_csv("Match.csv")
plt.figure(figsize=(10, 6))
sns.swarmplot(data=df, x="Toss_Decision", y="Match_Winner_Id", size=4)
plt.title("Match Winner IDs by Toss Decision")
plt.xlabel("Toss Decision")
plt.ylabel("Match Winner ID")
plt.show()


GRAPH 9: DONUT CHART - HOME GROUND WINS

Use this code to display home ground wins as a donut chart.

CODE:

import pandas as pd
import matplotlib.pyplot as plt

df = pd.read_csv("Match.csv")
team_pairs = pd.concat([
    df[["Opponent_Team_Id", "OpponentTeam name"]].rename(
        columns={"Opponent_Team_Id": "Team_ID", "OpponentTeam name": "Team_Name"}),
    df[["Match_Winner_Id", "Team name"]].rename(
        columns={"Match_Winner_Id": "Team_ID", "Team name": "Team_Name"}),
    df[["Match_Winner_Id", "OpponentTeam name"]].rename(
        columns={"Match_Winner_Id": "Team_ID", "OpponentTeam name": "Team_Name"})
]).dropna().drop_duplicates()
team_map = team_pairs.groupby("Team_ID")["Team_Name"].first()
df["Match_Winner_Name"] = df["Match_Winner_Id"].map(team_map)
home_wins = df[df["OpponentTeam name"] == df["Match_Winner_Name"]]
home_win_counts = home_wins["OpponentTeam name"].value_counts()

plt.figure(figsize=(9, 9))
plt.pie(home_win_counts, labels=home_win_counts.index, autopct="%1.1f%%",
        startangle=90, pctdistance=0.8,
        wedgeprops=dict(width=0.4, edgecolor="white"))
plt.text(0, 0, "Home
Wins", ha="center", va="center", fontsize=16, fontweight="bold")
plt.title("Home Ground Wins by Team")
plt.axis("equal")
plt.tight_layout()
plt.show()


GRAPH 10: 3D SCATTER PLOT - VENUE, TOSS DECISION AND WIN TYPE

Use this code to plot the three categorical variables using category codes.

CODE:

import pandas as pd
import matplotlib.pyplot as plt

from mpl_toolkits.mplot3d import Axes3D

df = pd.read_csv("Match.csv")
df["Venue_Code"] = df["Venue_Name"].astype("category").cat.codes
df["Toss_Code"] = df["Toss_Decision"].astype("category").cat.codes
df["WinType_Code"] = df["Win_Type"].astype("category").cat.codes

fig = plt.figure(figsize=(12, 8))
ax = fig.add_subplot(111, projection="3d")
scatter = ax.scatter(df["Venue_Code"], df["Toss_Code"], df["WinType_Code"],
                    c=df["WinType_Code"], cmap="viridis", s=40, alpha=0.7)
ax.set_title("3D Scatter Plot of Venue, Toss Decision and Win Type")
ax.set_xlabel("Venue")
ax.set_ylabel("Toss Decision")
ax.set_zlabel("Win Type")

venue_labels = df["Venue_Name"].astype("category").cat.categories
toss_labels = df["Toss_Decision"].astype("category").cat.categories
win_labels = df["Win_Type"].astype("category").cat.categories
ax.set_xticks(range(len(venue_labels)))
ax.set_xticklabels(venue_labels, rotation=45, ha="right")
ax.set_yticks(range(len(toss_labels)))
ax.set_yticklabels(toss_labels)
ax.set_zticks(range(len(win_labels)))
ax.set_zticklabels(win_labels)
plt.colorbar(scatter, ax=ax, label="Win Type Code")
plt.tight_layout()
plt.show()


SHORT EXPLANATION:
- The numerical summary displays mean, median, mode, skewness and kurtosis for numerical columns.
- Each graph has its own separate code. Run one graph code at a time.
- Bar, pie and donut charts show categorical counts.
- Scatter, box, line, violin, swarm and 3D scatter plots show different views of the data.
