LeetCode's Introduction to Pandas

May 17, 2026

Introduction

Introduction to Pandas is a study plan on LeetCodeLeetCode: 15 exercises in pandaspandas, the PythonPython library for tabular data. It walks from building a DataFrame by hand to chaining several operations into one expression. This post keeps every solution I submitted.

Creating and inspecting a DataFrame

Create a DataFrame from List

Turn a 2D list of student IDs and ages into a DataFrame with the columns student_id and age, keeping the rows in their original order.

import pandas as pd

def createDataframe(student_data: List[List[int]]) -> pd.DataFrame:
    return pd.DataFrame(student_data, columns=['student_id', 'age'])

Get the Size of a DataFrame

Given a players frame, report how many rows and how many columns it holds, as [rows, columns].

import pandas as pd

def getDataframeSize(players: pd.DataFrame) -> List[int]:
    return [players.shape[0], players.shape[1]]

Display the First Three Rows

Show the first three rows of an employees frame.

import pandas as pd

def selectFirstRows(employees: pd.DataFrame) -> pd.DataFrame:
    return employees.head(3)

Selecting and adding data

Select Data

From a students frame, return the name and age of the one student whose student_id is 101.

import pandas as pd

def selectData(students: pd.DataFrame) -> pd.DataFrame:
    return students.loc[students["student_id"] == 101, ["name", "age"]]

Create a New Column

A company is paying its employees a bonus: add a bonus column holding double each salary.

import pandas as pd

def createBonusColumn(employees: pd.DataFrame) -> pd.DataFrame:
    employees['bonus'] = (2 * employees['salary'])
    return employees

Cleaning

Drop Duplicate Rows

A customers frame repeats some addresses in its email column. Remove the duplicates, keeping the first occurrence of each.

import pandas as pd

def dropDuplicateEmails(customers: pd.DataFrame) -> pd.DataFrame:
    customersNoDuplicates = customers.drop_duplicates(subset=["email"], keep="first")
    return customersNoDuplicates

Drop Missing Data

Some rows of a students frame have no value in name. Remove those rows.

import pandas as pd

def dropMissingData(students: pd.DataFrame) -> pd.DataFrame:
    return students.dropna(subset="name")

Modify Columns

A company is giving a pay rise: double every value already in the salary column, rather than adding a second one.

import pandas as pd

def multiplySalaryBy2(salary: int) -> int:
    return salary*2

def modifySalaryColumn(employees: pd.DataFrame) -> pd.DataFrame:
    employees['salary'] = employees['salary'].apply(multiplySalaryBy2)
    return employees

Rename Columns

Rename four columns of a students frame — id to student_id, first to first_name, last to last_name, age to age_in_years.

import pandas as pd

def renameColumns(students: pd.DataFrame) -> pd.DataFrame:
    rename_students = students.rename(
        columns={
            "id": "student_id",
            "first": "first_name",
            "last": "last_name",
            "age": "age_in_years"
            },
    )
    return rename_students

Change Data Type

The grade column of a students frame was stored as floats by mistake. Convert it to integers.

import pandas as pd

def changeDatatype(students: pd.DataFrame) -> pd.DataFrame:
    students_newtype = {'grade': int}
    students2 = students.astype(students_newtype)
    return students2

Fill Missing Data

Some rows of a products frame have no quantity. Fill those missing values with 0 instead of dropping the rows.

import pandas as pd

def fillMissingValues(products: pd.DataFrame) -> pd.DataFrame:
    products["quantity"] = products["quantity"].fillna(0)
    return products

Reshaping

Reshape Data: Concatenate

Two frames carry the same three columns. Stack them vertically into a single frame.

import pandas as pd

def concatenateTables(df1: pd.DataFrame, df2: pd.DataFrame) -> pd.DataFrame:
    return pd.concat([df1, df2])

Reshape Data: Pivot

A weather frame holds one row per city and month. Reshape it so that each row is a month and each city becomes its own column.

import pandas as pd

def pivotTable(weather: pd.DataFrame) -> pd.DataFrame:
    return weather.pivot(index="month", columns="city", values="temperature")

Reshape Data: Melt

A report frame holds one column per quarter. Reshape it so that each row is one product in one quarter.

import pandas as pd

def meltTable(report: pd.DataFrame) -> pd.DataFrame:
    return report.melt(
        id_vars=["product"],
        value_vars=["quarter_1", "quarter_2", "quarter_3", "quarter_4"],
        var_name='quarter',
        value_name='sales'
        )

Putting it together

Method Chaining

List the names of the animals weighing strictly more than 100 kilograms, heaviest first.

import pandas as pd

def findHeavyAnimals(animals: pd.DataFrame) -> pd.DataFrame:
    return animals.sort_values(by=['weight'], ascending=False).loc[animals['weight'] > 100, ['name']]