LearnPy Hub
Data ScienceIntermediateLesson 26 of 32

Pandas: DataFrames

Watch the ideaA DataFrame is a table
df = pd.DataFrame({"name": ["Mim", "Rafi", "Tania"],
                   "marks": [72, 88, 65]})
df
namemarks
0Mim72
1Rafi88
2Tania65

Rows have an index on the left; each column has a name.

1Level 1 · BasicsBasics

pandas is Python's spreadsheet. Its main object, the DataFrame, is a table with named columns and labelled rows. Analysts, scientists and businesses use pandas to load, explore and summarise data. If you've used Excel, many ideas will feel familiar.

The first pandas example downloads the library into your browser, which can take a little while.

Series and DataFrame

  • A Series is one column: values with an index (labels).
  • A DataFrame is a table made of several Series that share the same index.
import pandas as pd       # pd is the standard nickname

df = pd.DataFrame({
    "name":  ["Mim", "Rafi", "Sara"],
    "dept":  ["CSE", "EEE", "CSE"],
    "cgpa":  [3.82, 3.41, 3.95],
})

A dictionary of lists becomes a table: keys are column names, and each list fills a column. Usually you'd load real data instead: pd.read_csv("students.csv").

First look at the data

CodeShows
df.head() / df.tail()first / last 5 rows
df.shape(rows, columns)
df.columnscolumn names
df.describe()count, mean, min, max and more for number columns
df["dept"].value_counts()how often each value appears

Selecting columns and rows

df["cgpa"]                 # one column (a Series)
df[["name", "cgpa"]]       # several columns (note the double brackets)
df.loc[0]                  # row with index label 0
df.loc[0, "name"]          # one value
df.iloc[-1]                # last row, by position

Filtering rows

Exactly like NumPy masks: a condition gives True/False for each row.

df[df["cgpa"] >= 3.5]
df[(df["dept"] == "CSE") & (df["cgpa"] > 3.9)]   # use & and |, with brackets

New columns and sorting

df["percent"] = df["cgpa"] / 4 * 100       # calculated column
df.sort_values("cgpa", ascending=False)    # highest first

Column maths

df["cgpa"].mean(), .max(), .sum(), .round(1) and string tools like df["name"].str.upper() all work on whole columns at once.

Reading and saving data

pd.read_csv has options for real-world files:

pd.read_csv("data.csv", sep=";")               # columns separated by ; instead of ,
pd.read_csv("data.csv", usecols=["name", "cgpa"])  # only some columns
pd.read_csv("data.csv", nrows=1000)            # just the first 1000 rows
pd.read_csv("data.csv", index_col="id")        # use a column as the row labels
pd.read_csv("data.csv", na_values=["-", "N/A"])  # extra markers for missing values

Save with df.to_csv("clean.csv", index=False) (index=False stops pandas writing the row numbers as an extra column). There are matching read_excel/to_excel and read_json/to_json functions.

Column types: info() and dtypes

df.info() lists every column with its type and how many values are present. The common types are int64, float64, bool, datetime64 and object (text; shown as str in the newest pandas). df.select_dtypes("number") keeps only the number columns, and df["credits"].astype(int) converts a column.

loc and iloc in detail

df.loc[...]df.iloc[...]
Selects bylabels (index values, column names)positions (0, 1, 2, ...)
Slice endincluded: df.loc[0:2] gives 3 rowsexcluded: df.iloc[0:2] gives 2 rows
Rows and columnsdf.loc[0:2, "name":"cgpa"]df.iloc[0:2, 0:3]
With a conditiondf.loc[df["cgpa"] > 3.5, "name"](not allowed)

loc is also the safe way to change values: df.loc[df["dept"] == "CSE", "fee"] = 5000 sets the fee for every CSE row.

More ways to filter

df[df["dept"].isin(["CSE", "EEE"])]        # one of several values
df[df["cgpa"].between(3.0, 3.5)]           # inside a range (ends included)
df[df["name"].str.contains("a")]           # text contains a letter or word
df[~df["dept"].isin(["BBA"])]              # ~ means NOT
df.query("cgpa > 3.5 and dept == 'CSE'")    # the same idea written as text

Changing the table

  • df.rename(columns={"cgpa": "gpa"}) renames; df.drop(columns=["credits"]) removes columns; df.drop(index=[0, 3]) removes rows.
  • df["dept"].replace({"CSE": "Computer Science"}) swaps values.
  • df["grade"] = df["cgpa"].map(lambda g: "A" if g >= 3.75 else "B") transforms each value; df.apply(func, axis=1) runs a function on each row.
  • df.set_index("name") makes a column the row labels, and df.reset_index() turns the labels back into a column.

Sorting and ranking

df.sort_values(["dept", "cgpa"], ascending=[True, False]) sorts by department, then by CGPA within each department. df.nlargest(3, "cgpa") and df.nsmallest(3, "cgpa") are shortcuts for "top 3", and df["cgpa"].rank(ascending=False) gives each row its position.

Key points: import pandas as pd; a DataFrame is a table of columns; df["col"] selects, df[condition] filters, df.loc[] and df.iloc[] pick rows; combine conditions with & and |.

See it in actionA DataFrame is a table

Watch the table appear, get filtered, and gain a new column.

Step-by-step

Try it yourselfExample 1: Your first DataFrame

A dictionary of lists becomes a table.

example_1.py
Output appears here
Fill in the blanks

Your first DataFrame

Fill the blanks so the program builds a DataFrame and prints how many rows it has: 3.

blanks.py
import pandas as pd
df = pd.({"name": ["Mim", "Joy", "Tara"], "age": [12, 13, 12]})
print((df))

Example 2: Exploring

describe() summarises number columns; value_counts() counts categories.

example_2.py
Output appears here
Fix the bug

Wrong column name

This should print the average score, 81.0, but it crashes. Look at the column names and fix it.

buggy.py

Example 3: Selecting and filtering

Conditions pick rows; double brackets pick several columns.

example_3.py
Output appears here
Fill in the blanks

Older students

Fill the blanks so only students older than 12 are kept and their names are printed as a list: ['Joy'].

blanks.py
import pandas as pd
df = pd.DataFrame({"name": ["Mim", "Joy", "Tara"], "age": [12, 13, 12]})
older = df[df[]  12]
print(list(older["name"]))

Example 4: New columns and sorting

Column maths applies to every row at once.

example_4.py
Output appears here
Your turn

Total price column

Add a column total equal to price × qty, then print the sum of that column: 270.

my_code.py
Your turn

Who scored highest?

Sort the table by score from highest to lowest and print the first name: Joy.

my_code.py

Example 5: Reading a CSV

Here we write a small CSV file first, then load it, just as you would with a real file.

example_5.py
Output appears here

Example 6: Reading options and saving

A semicolon-separated file with '-' for missing values. sep, na_values and usecols handle it; to_csv writes the clean version.

example_6.py
Output appears here

Example 7: Types with info() and select_dtypes

The credits column arrived as text, so its maths is wrong until astype(int) converts it.

example_7.py
Output appears here

Example 8: loc and iloc side by side

The row labels here are student ids, not 0, 1, 2. loc uses the ids and includes the slice end; iloc counts positions and excludes it.

example_8.py
Output appears here

Example 9: isin, between, contains and query

Four quick filters and their NOT versions.

example_9.py
Output appears here

Example 10: rename, drop, replace, map and apply

map changes one column value by value; apply with axis=1 sees a whole row, so it can use several columns.

example_10.py
Output appears here

Example 11: Sorting by several columns and ranking

Sort by department, then best CGPA first inside each one. nlargest is a shortcut for the top rows; rank numbers every row.

example_11.py
Output appears here

2Level 2 · Intermediateloc, iloc, apply and value_counts

loc and iloc

df.loc[rows, columns] selects by label and condition: df.loc[df["marks"] > 80, ["name", "marks"]]. df.iloc[0:3, 1] selects by position. Use loc when changing values: df.loc[df["marks"] < 33, "grade"] = "F".

map and apply

df["grade"].map({"A": 4, "B": 3}) translates values; df["name"].apply(len) runs a function on each value. Prefer built-in vectorized operations when they exist.

Counting and text

df["city"].value_counts() counts categories. The .str accessor brings string methods to a whole column: df["name"].str.upper(), .str.contains("a").

See it in actionSelecting and updating with loc

Watch the DataFrame change after the loc assignment.

Step-by-step

Example 12: map, apply, str and value_counts

Each line adds one new column built from an existing one.

example_12.py
Output appears here

3Level 3 · AdvancedMethod chaining, rank and rolling windows

Method chaining

Write a whole analysis as one readable pipeline: df.query(...).assign(...).sort_values(...).head(). assign adds columns without changing the original; query("marks > 80 and city == 'Dhaka'") filters with a readable string.

rank and transform

df["marks"].rank(ascending=False, method="min") gives competition ranks with ties. groupby(...).transform("mean") puts each group's average back on every row.

Rolling windows

s.rolling(3).mean() is a 3-day moving average, which smooths noisy daily data. s.cumsum() and s.pct_change() track totals and growth.

Memory and speed

df.info(memory_usage="deep") shows memory use; converting repeated text to "category" often saves a lot.

Example 13: A chained analysis with ranks

Read the chain top to bottom like a recipe.

example_13.py
Output appears here

Example 14: Moving averages and category memory

The 3-day average is smoother than the daily numbers.

example_14.py
Output appears here
Common mistakeUse & and | (not and/or) to combine conditions, and wrap each condition in brackets: df[(df.a > 1) & (df.b < 5)]. Without the brackets you'll get a confusing error about the "truth value of a Series".
Exercise · predict the output

What does this print?

import pandas as pd
df = pd.DataFrame({"x": [5, 12, 7, 20]})
print(len(df[df["x"] > 6]))
Quick quiz · 7 questions
1. What is a DataFrame?
2. How do you select two columns, name and cgpa?
3. What does df.shape return for 100 rows and 5 columns?
4. Which keeps rows where age is over 18 AND city is Dhaka?
5. What does df.iloc[0] give?
6. df has the index 0, 1, 2, 3, 4. How many rows does df.loc[1:3] return?
7. Which keeps rows whose dept is CSE or EEE?
Ready to practice pandas: dataframes?

50 graded problems are waiting in Topic Practice.

Practice this topic →
Python Pandas: DataFrames · LearnPy Hub