Home β€Ί Curriculum β€Ί Pandas Data Analysis
Updated for Python 3.12+ Β· November 2026

🐼 Pandas Data Analysis
in Python

Learn pandas from scratch: Series, DataFrames, CSV text, loc and iloc, filtering, missing data, groupby, merge, pivot_table, string and date tools, with runnable code.

Intermediate 9 lessonsβ‰ˆ 44 min read by Glenn Pansensoy

What this lesson is about

Pandas is the library most Python programmers reach for when data arrives as a table: a spreadsheet export, a CSV from a colleague, the result of a database query. It gives you the DataFrame, a table with labelled rows and columns, and a large toolkit for cleaning it, reshaping it and summarising it. Questions such as 'what was the average order value per city last month?' become two or three readable lines instead of a page of loops.

Under the hood a DataFrame is a collection of columns, each one a Series with its own type, built on top of NumPy arrays. That is why pandas feels fast, and also why it rewards a particular way of thinking: you operate on whole columns at once, you select rows with True/False masks, and you describe a summary (group by this, aggregate that) rather than writing the loop yourself. If you have read the NumPy lesson, a lot of this will feel familiar.

I have ordered the page the way I would teach it in person. We start with Series and DataFrames, build tables from dictionaries and from CSV text, then select data with loc and iloc, filter and sort, handle missing values, group and aggregate, combine tables with merge and pivot_table, use the string and datetime tools, and finish with a small end-to-end analysis. Every example runs in your browser, and I print results with to_string() or plain numbers so you see exactly what I see.

What you will learn

  • βœ“Create Series and DataFrames from lists, dictionaries and CSV text
  • βœ“Select rows and columns with loc, iloc and boolean masks
  • βœ“Filter and sort data using conditions, isin, between and sort_values
  • βœ“Find, fill and drop missing values without hiding problems
  • βœ“Summarise data with groupby and agg, including named aggregations
  • βœ“Combine tables with merge and reshape them with pivot_table
  • βœ“Use the .str and .dt accessors for text and dates
  • βœ“Put the pieces together in a small, readable analysis

Why programmers should learn this

  • β˜…Real-world data is almost always tabular, and pandas is the common language for it across analytics, finance, science and operations work, so reading other people's data code becomes much easier.
  • β˜…A grouped summary that takes a page of loops and dictionaries takes one line in pandas, which means fewer bugs and analysis that a colleague can actually read and check.
  • β˜…Cleaning is where most data time goes. Pandas gives you named, testable steps for fixing types, missing values and messy text instead of manual spreadsheet edits you cannot repeat.
  • β˜…Merging tables is the same idea as a SQL join, so learning merge also strengthens your database thinking and lets you combine data that lives in different files.
  • β˜…Pandas feeds the rest of the data stack: scikit-learn models, Matplotlib charts and many reporting tools accept DataFrames directly, so this is the gateway skill for data science.

Series: one labelled column

A Series is a one-dimensional array of values with an index, a label for each value. Think of it as a column in a spreadsheet where the row numbers are real, usable labels rather than just positions. If you do not supply an index, pandas numbers the rows 0, 1, 2 and so on, but you can use anything: dates, product codes, names.

Arithmetic on a Series is vectorised: prices * 1.1 multiplies every value, and prices + other adds two Series by matching their labels, not their positions. That label alignment is one of pandas' most useful and most surprising features. Labels present in only one Series produce NaN, which stands for 'not a number', pandas' marker for a missing value.

Series also come with summary methods such as sum, mean, max, idxmax (the label of the maximum) and describe. I print scalars and use round here so the output is the same on every pandas version.

python
import pandas as pd

prices = pd.Series([2.5, 4.0, 3.2], index=["tea", "coffee", "juice"])
print(prices.to_string())
print(prices["coffee"], prices.iloc[0])
print((prices * 1.1).round(2).to_string())
print(prices.sum(), round(prices.mean(), 3), prices.idxmax())

a = pd.Series([1, 2, 3], index=["x", "y", "z"])
b = pd.Series([10, 20, 30], index=["y", "z", "w"])
print((a + b).to_string())
Expected output
tea       2.5
coffee    4.0
juice     3.2
4.0 2.5
tea       2.75
coffee    4.40
juice     3.52
9.7 3.233 coffee
w     NaN
x     NaN
y    12.0
z    23.0

Line by line

  1. 1Import pandas under its usual name pd.
  2. 3-4Create a Series with custom labels and print it. to_string() gives a stable plain-text layout.
  3. 5Look up one value by label (prices['coffee']) and one by position (iloc[0]).
  4. 6Multiply every price by 1.1 and round to two decimals; the labels are kept.
  5. 7Scalar summaries: total, mean rounded to 3 places, and the label with the highest price.
  6. 9-11Add two Series. Pandas matches labels: y and z are added, while x and w exist in only one Series and become NaN.
ℹ️

Because of NaN, a Series that should hold integers can turn into floats after label alignment. That is expected: plain integers cannot represent a missing value.

DataFrames from dictionaries and CSV text

A DataFrame is a table: an ordered collection of Series that share one index. The most direct way to make one is from a dictionary where each key is a column name and each value is a list of that column's values. Every list must have the same length.

In practice your data usually starts in a file. pd.read_csv accepts a file path, but it also accepts any file-like object, so io.StringIO lets you treat a string as if it were a file. I use that trick throughout this page because it keeps every example self-contained and runnable in the browser; in your own projects you would simply pass the path of your CSV.

After loading, always look before you leap. df.shape gives rows and columns, df.columns lists the names, df.dtypes shows each column's type, and df.head() shows the first rows. Checking dtypes early catches the most common problem in real data: numbers that were read as text because one cell contained a stray symbol.

From a dictionary
import pandas as pd

df = pd.DataFrame({
    "name": ["Ana", "Ben", "Cara", "Dev"],
    "age": [28, 35, 41, 23],
    "city": ["Cebu", "Davao", "Cebu", "Manila"],
})
print(df.to_string())
print(df.shape, list(df.columns))
print(df["age"].dtype)
df["age_next_year"] = df["age"] + 1
print(df[["name", "age_next_year"]].to_string(index=False))
Expected output
   name  age    city
0   Ana   28    Cebu
1   Ben   35   Davao
2  Cara   41    Cebu
3   Dev   23  Manila
(4, 3) ['name', 'age', 'city']
int64
name  age_next_year
 Ana             29
 Ben             36
Cara             42
 Dev             24

Line by line

  1. 3-7Each dictionary key becomes a column; the lists become the column values.
  2. 8Print the table without relying on the default display.
  3. 9-10shape is (rows, columns); df['age'].dtype shows the column holds 64-bit integers.
  4. 11Assigning to a new column name creates it, computed for every row at once.
  5. 12Select two columns using a list inside the brackets and hide the index.
From CSV text
import io
import pandas as pd

csv_text = """order_id,customer,amount,paid
1001,Ana,250.50,yes
1002,Ben,99.99,no
1003,Ana,410.00,yes
1004,Cara,15.25,yes
"""
orders = pd.read_csv(io.StringIO(csv_text))
print(orders.to_string())
print(orders.dtypes.astype(str).to_string())
print(round(orders["amount"].sum(), 2))
Expected output
   order_id customer  amount paid
0      1001      Ana  250.50  yes
1      1002      Ben   99.99   no
2      1003      Ana  410.00  yes
3      1004     Cara   15.25  yes
order_id      int64
customer        str
amount      float64
paid            str
775.74

Line by line

  1. 1-2io provides StringIO, a fake file made from a string.
  2. 4-9A small CSV held in a triple-quoted string: a header line, then one row per order.
  3. 10read_csv parses it, guessing a type for each column (integers, floats, text).
  4. 11Print the whole table.
  5. 12Show each column's dtype; astype(str) keeps the text identical across pandas versions.
  6. 13Total of the amount column, rounded to 2 decimals.
πŸ’‘

read_csv has options you will use constantly: sep=';' for other delimiters, usecols to load only some columns, dtype to force types and parse_dates to read date columns properly.

Selecting data with loc, iloc and masks

Pandas gives you two precise ways to pick data. loc selects by *label*: row labels and column names. iloc selects by *integer position*, like list indexing. Remembering which is which saves a lot of confusion: loc is about names, iloc is about places.

One difference trips people up: slices with loc include the end label (loc['b':'d'] returns b, c and d), while slices with iloc exclude the end position, exactly like normal Python slices. That is because labels have no natural 'one past the end', so pandas includes the last one.

Both accept a row selector and a column selector separated by a comma, and loc also accepts a boolean mask for rows. Prefer df.loc[mask, 'col'] over chained forms like df[mask]['col'] = ... when you assign, because the single loc call is unambiguous about modifying the original table.

python
import pandas as pd

df = pd.DataFrame(
    {"score": [88, 92, 75, 60], "team": ["red", "blue", "red", "blue"]},
    index=["a", "b", "c", "d"],
)
print(df.loc["b", "score"])
print(df.loc["b":"c", ["score"]].to_string())
print(df.iloc[0:2, 0].to_string())
print(df.iloc[-1].to_dict())

df.loc[df["score"] < 70, "score"] = 70
print(df["score"].tolist())
Expected output
92
   score
b     92
c     75
a    88
b    92
{'score': 60, 'team': 'blue'}
[88, 92, 75, 70]

Line by line

  1. 3-6Build a table with custom row labels a to d.
  2. 7loc with a row label and a column name returns one value.
  3. 8A label slice from b to c includes both ends; the column list keeps the result a DataFrame.
  4. 9iloc[0:2, 0] takes positions 0 and 1 (end excluded) of the first column.
  5. 10iloc[-1] is the last row, turned into a dictionary for tidy printing.
  6. 12-13Use a boolean mask inside loc to set every score below 70 to 70, then print the column as a list.
⚠️

Avoid df[df['x'] > 1]['y'] = 0. That chained assignment may modify a temporary copy and leave your table unchanged. Use df.loc[df['x'] > 1, 'y'] = 0.

Filtering and sorting

Filtering means keeping the rows where a condition is true. A comparison such as df['age'] > 30 returns a Series of True/False values, and passing that mask inside square brackets keeps only the True rows. Combine conditions with & (and), | (or) and ~ (not), and wrap each condition in parentheses because those operators bind more tightly than comparisons.

Pandas also has readable helpers: isin([...]) tests membership in a list, between(a, b) tests a range (inclusive by default) and str.contains tests text, which I cover later. Together they cover most everyday filters.

Sorting uses sort_values(by, ascending=...). Pass a list to sort by several columns, and a matching list for ascending to mix directions. Sorting returns a new table, and the original index labels travel with each row; call reset_index(drop=True) when you want fresh 0, 1, 2 numbering. For the top few rows, nlargest and nsmallest are shorter than sort plus head.

python
import pandas as pd

people = pd.DataFrame({
    "name": ["Ana", "Ben", "Cara", "Dev", "Eli"],
    "age": [28, 35, 41, 23, 35],
    "city": ["Cebu", "Davao", "Cebu", "Manila", "Davao"],
})
older = people[people["age"] > 30]
print(older["name"].tolist())

both = people[(people["city"] == "Cebu") & (people["age"] < 40)]
print(both["name"].tolist())
print(people[people["city"].isin(["Davao", "Manila"])]["name"].tolist())
print(people[people["age"].between(25, 35)]["name"].tolist())

ranked = people.sort_values(["age", "name"], ascending=[False, True])
print(ranked.reset_index(drop=True).to_string())
print(people.nlargest(2, "age")["name"].tolist())
Expected output
['Ben', 'Cara', 'Eli']
['Ana']
['Ben', 'Dev', 'Eli']
['Ana', 'Ben', 'Eli']
   name  age    city
0  Cara   41    Cebu
1   Ben   35   Davao
2   Eli   35   Davao
3   Ana   28    Cebu
4   Dev   23  Manila
['Cara', 'Ben']

Line by line

  1. 3-7A small table of five people.
  2. 8-9A single condition: people older than 30.
  3. 11-12Two conditions combined with &; the parentheses are required.
  4. 13isin keeps rows whose city is in the given list.
  5. 14between(25, 35) includes both 25 and 35.
  6. 16-17Sort by age descending, then by name ascending for ties, and renumber the index.
  7. 18nlargest(2, 'age') returns the two oldest rows.

Missing data

Real data has gaps. Pandas represents a missing number as NaN and has tools to find, fill and remove it. isna() returns a True/False mask, and df.isna().sum() is the fastest way to count missing values per column, which I run on almost every new dataset.

There are two broad responses. Dropping with dropna() removes rows (or columns) that contain gaps, which is simple but throws information away. Filling with fillna(value) replaces them, for example with zero, with the column mean or median, or with a label such as 'unknown'. Neither is always right: it depends on what a missing value means. A missing sales figure might genuinely be zero, while a missing age is unknown and a zero would badly distort an average.

Remember that most aggregations skip NaN by default, so mean() quietly averages only the values that are present. That is convenient but can hide the problem, so count the gaps before you trust a summary. I assign the filled result back to the column rather than using inplace=True, which is discouraged because it behaves inconsistently.

python
import io
import pandas as pd

text = """name,age,score
Ana,28,90
Ben,,75
Cara,41,
Dev,23,60
"""
df = pd.read_csv(io.StringIO(text))
print(df.isna().sum().to_string())
print(df["age"].mean(), df["score"].mean())

clean = df.dropna()
print(len(clean), clean["name"].tolist())

filled = df.copy()
filled["age"] = filled["age"].fillna(filled["age"].median())
filled["score"] = filled["score"].fillna(0)
print(filled.to_string())
Expected output
name     0
age      1
score    1
30.666666666666668 75.0
2 ['Ana', 'Dev']
   name   age  score
0   Ana  28.0   90.0
1   Ben  28.0   75.0
2  Cara  41.0    0.0
3   Dev  23.0   60.0

Line by line

  1. 4-8CSV text with two blanks: Ben has no age, Cara has no score. Blanks are read as NaN.
  2. 10-11Count missing values per column, then take means; mean ignores the gaps.
  3. 13-14dropna() removes every row with any missing value, leaving two rows.
  4. 16-19Work on a copy. Fill age with the column median and score with 0, assigning back to the columns.
  5. 20Print the repaired table.
πŸ’‘

Decide what a blank means before you fill it, and record that decision in a comment. A silent fillna(0) is one of the most common ways to produce plausible-looking wrong numbers.

groupby and agg: split, apply, combine

groupby is the heart of pandas analysis. It splits the table into groups that share a key (for example one group per city), applies a calculation to each group and combines the results into a new table. The pattern is often called split-apply-combine, and once you see it you will notice it everywhere: totals per month, averages per category, counts per user.

The simplest form picks a column and a function: df.groupby('city')['sales'].sum(). For several summaries at once use agg. Named aggregation, written agg(total=('sales', 'sum'), orders=('sales', 'count')), is my favourite style because you choose the output column names and the result reads like a sentence. Group by two columns by passing a list.

By default the group keys become the index of the result. Call reset_index() to turn them back into ordinary columns, which is usually what you want before merging or charting. Groups are sorted by key unless you pass sort=False.

python
import pandas as pd

sales = pd.DataFrame({
    "city": ["Cebu", "Cebu", "Davao", "Davao", "Davao", "Manila"],
    "product": ["tea", "jam", "tea", "tea", "jam", "tea"],
    "amount": [100, 150, 80, 120, 60, 200],
})
print(sales.groupby("city")["amount"].sum().to_string())

summary = sales.groupby("city").agg(
    total=("amount", "sum"),
    orders=("amount", "count"),
    biggest=("amount", "max"),
).reset_index()
print(summary.to_string(index=False))

pair = sales.groupby(["city", "product"])["amount"].mean()
print(pair.round(1).to_string())
Expected output
city
Cebu      250
Davao     260
Manila    200
  city  total  orders  biggest
  Cebu    250       2      150
 Davao    260       3      120
Manila    200       1      200
city    product
Cebu    jam        150.0
        tea        100.0
Davao   jam         60.0
        tea        100.0
Manila  tea        200.0

Line by line

  1. 3-7Six sales rows across three cities and two products.
  2. 8Group by city and add up the amounts; the result is a Series indexed by city.
  3. 10-14Named aggregation computes three summaries per city with names we choose.
  4. 14reset_index() turns the city index back into a normal column.
  5. 17-18Group by two keys: the result has a two-level index (city, product) with the mean amount for each pair.
ℹ️

count counts non-missing values, while size counts rows including missing ones. They differ when a column has gaps.

Combining tables: merge and pivot_table

Data is rarely in one table. Orders live in one place and customer details in another, linked by a shared key such as customer_id. pd.merge(left, right, on='key') joins them, matching rows by that key exactly like a SQL join (see the SQLite lesson for the database version).

The how argument chooses what happens to unmatched rows. inner (the default) keeps only keys present in both tables. left keeps every row of the left table and fills the right side with NaN when there is no match, which is the join I use most often because it never silently drops my main data. outer keeps everything from both sides.

pivot_table reshapes a long table into a compact grid: one variable becomes the rows, another becomes the columns, and an aggregation fills the cells. It is the pandas version of a spreadsheet pivot table, and it is the quickest way to see a two-way summary. fill_value=0 replaces empty cells, and aggfunc picks the calculation.

python
import pandas as pd

orders = pd.DataFrame({
    "order": [1, 2, 3, 4],
    "cust": ["a", "b", "a", "z"],
    "amount": [50, 20, 30, 10],
})
custs = pd.DataFrame({"cust": ["a", "b", "c"], "name": ["Ana", "Ben", "Cara"]})

inner = orders.merge(custs, on="cust")
print(inner.to_string(index=False))
left = orders.merge(custs, on="cust", how="left")
print(left["name"].isna().sum(), len(left))

sales = pd.DataFrame({
    "city": ["Cebu", "Cebu", "Davao", "Davao", "Davao"],
    "product": ["tea", "jam", "tea", "tea", "jam"],
    "amount": [100, 150, 80, 120, 60],
})
grid = sales.pivot_table(index="city", columns="product",
                         values="amount", aggfunc="sum", fill_value=0)
print(grid.to_string())
Expected output
 order cust  amount name
     1    a      50  Ana
     2    b      20  Ben
     3    a      30  Ana
1 4
product  jam  tea
city             
Cebu     150  100
Davao     60  200

Line by line

  1. 3-7Four orders; customer z does not exist in the customer table.
  2. 8A small customer table; customer c has no orders.
  3. 10-11The inner merge keeps only orders whose customer exists in both tables, so order 4 disappears.
  4. 12-13A left merge keeps all four orders; the unmatched one gets NaN for name, which we count.
  5. 15-19Sales per city and product.
  6. 20-22pivot_table builds a grid with cities as rows and products as columns, summing amounts and filling empty cells with 0.
⚠️

After any merge, compare row counts before and after. If the key is duplicated in the right table, rows multiply and totals silently inflate.

Text and dates: the .str and .dt accessors

Text columns have a .str accessor that applies string methods to every value at once: str.lower, str.strip, str.replace, str.contains, str.split, str.len. This is how you clean messy labels such as ' Cebu ' versus 'cebu' before grouping, so that one city is not counted as three. Missing values pass through safely.

Dates deserve proper date types. pd.to_datetime converts text such as '2025-03-14' into real timestamps, and the .dt accessor then exposes parts: dt.year, dt.month, dt.day_name(), dt.dayofweek. Date subtraction gives a timedelta, and .dt.days turns it into a number. Compare this with Python's own datetime module, which pandas builds on.

Once dates are real, grouping by month or weekday is a one-liner. Passing format='%Y-%m-%d' to to_datetime is faster and avoids ambiguity about day-first versus month-first dates.

python
import pandas as pd

df = pd.DataFrame({
    "city": [" Cebu ", "davao", "CEBU", "Manila "],
    "day": ["2025-03-14", "2025-03-15", "2025-04-02", "2025-04-20"],
    "amount": [10, 20, 30, 40],
})
df["city"] = df["city"].str.strip().str.title()
print(df["city"].tolist())
print(df["city"].str.contains("Ce").sum())
print(df["city"].str.len().tolist())

df["day"] = pd.to_datetime(df["day"], format="%Y-%m-%d")
df["month"] = df["day"].dt.month
df["weekday"] = df["day"].dt.day_name()
print(df[["month", "weekday"]].to_string(index=False))
print((df["day"].max() - df["day"].min()).days)
print(df.groupby("month")["amount"].sum().to_string())
Expected output
['Cebu', 'Davao', 'Cebu', 'Manila']
2
[4, 5, 4, 6]
 month   weekday
     3    Friday
     3  Saturday
     4 Wednesday
     4    Sunday
37
month
3    30
4    70

Line by line

  1. 3-7Messy city labels (extra spaces, mixed case) and dates stored as text.
  2. 8-9Chain strip then title to normalise every label; now 'CEBU' and ' Cebu ' are the same.
  3. 10contains('Ce') gives a True/False mask; summing it counts matches.
  4. 11Length of each cleaned label.
  5. 13Convert the text column to real timestamps using an explicit format.
  6. 14-16Extract the month number and weekday name into new columns.
  7. 17Subtracting dates gives a timedelta; .days is the whole-day count between first and last.
  8. 18Group by month and total the amounts.

A mini analysis walkthrough

Let me put everything together in a small, realistic workflow: load, check, clean, enrich, summarise. The data is a tiny export of shop orders with deliberate flaws, a missing quantity, inconsistent product casing and dates stored as text, because the flaws are what real projects are made of.

My order of work is always the same. First inspect: shape, dtypes, missing counts. Second clean: fix types and text, decide how to treat gaps. Third derive: add the columns the question needs, here revenue and month. Finally summarise with groupby and sort so the answer is the first thing you see. Each step is a named line, which makes the analysis easy to rerun when new data arrives.

Notice that I never loop over rows. Every step operates on whole columns. When you catch yourself writing for index, row in df.iterrows(), it is worth pausing to ask whether a column expression, a groupby or a merge would say the same thing more clearly and much faster.

python
import io
import pandas as pd

raw = """date,product,qty,price
2025-01-05,Tea,3,2.50
2025-01-09,coffee,2,4.00
2025-01-20,TEA,,2.50
2025-02-02,Coffee,5,4.00
2025-02-14,tea,4,2.50
2025-02-21,juice,1,3.20
"""
df = pd.read_csv(io.StringIO(raw))
print(df.shape, int(df["qty"].isna().sum()))

df["product"] = df["product"].str.lower()
df["date"] = pd.to_datetime(df["date"])
df["qty"] = df["qty"].fillna(1)
df["revenue"] = df["qty"] * df["price"]
df["month"] = df["date"].dt.month

report = (
    df.groupby("product")
      .agg(units=("qty", "sum"), revenue=("revenue", "sum"))
      .sort_values("revenue", ascending=False)
      .reset_index()
)
print(report.to_string(index=False))
by_month = df.pivot_table(index="month", columns="product",
                          values="revenue", aggfunc="sum", fill_value=0)
print(by_month.round(2).to_string())
print(round(df["revenue"].sum(), 2))
Expected output
(6, 4) 1
product  units  revenue
 coffee    7.0     28.0
    tea    8.0     20.0
  juice    1.0      3.2
product  coffee  juice   tea
month                       
1           8.0    0.0  10.0
2          20.0    3.2  10.0
51.2

Line by line

  1. 4-10Raw CSV text with flaws: one blank quantity, product names in mixed case.
  2. 11-12Inspect first: six rows by four columns and one missing quantity.
  3. 14Lower-case the product names so tea, Tea and TEA become one group.
  4. 15Convert the dates from text to timestamps.
  5. 16Assume a missing quantity means one unit; this is a decision I would note in a comment.
  6. 17-18Derive revenue per row and the month number.
  7. 20-25Group by product, compute units and revenue with named aggregations, sort by revenue and tidy the index.
  8. 27-29A product-by-month revenue grid, with 0 where nothing sold.
  9. 30The grand total as a sanity check against the grid.
πŸ’‘

End every analysis with a sanity check, such as the grand total, that you can verify by another route. If two routes disagree, you have found a bug before anyone else did.

Common mistakes

❌ Using chained assignment

Writing df[df['a'] > 1]['b'] = 0 may change a temporary copy instead of your table. Use one loc call, df.loc[df['a'] > 1, 'b'] = 0, so the intent is unambiguous and the original really changes.

❌ Forgetting parentheses around conditions

In df[df['a'] > 1 & df['b'] < 5] Python applies & before the comparisons and raises an error. Wrap each condition in parentheses and use &, |, ~, not and, or, not.

❌ Trusting types after read_csv

A single stray character such as a currency symbol turns a whole numeric column into text. Always check df.dtypes after loading, and convert with pd.to_numeric(col, errors='coerce') when you need to.

❌ Filling missing values without thinking

fillna(0) makes a gap look like a real measurement and drags averages down. Count gaps first, decide what a blank means for that column, and write the decision down.

❌ Looping over rows with iterrows

Row loops are slow and hide the data-flow. A column expression, groupby, merge or apply is almost always shorter and quicker. Reach for a loop only when the logic really cannot be expressed on whole columns.

Quick quiz

Tap an answer. I explain every one, right or wrong.

Q1. What is the difference between loc and iloc?

Q2. Which expression keeps rows where age is over 30 AND city is Cebu?

Q3. After a + b where the Series have different labels, what do labels present in only one Series become?

Q4. Which merge keeps every row of the left table even when there is no match?

Q5. What does df.groupby('city').agg(total=('amount', 'sum')) produce?

Q6. Why convert a date column with pd.to_datetime before analysis?

Frequently asked questions

Use pandas when your data is naturally a table and you need filtering, grouping, joining or summarising. For a handful of values, plain Python is simpler. Pandas earns its weight once the question starts with 'for each' or 'per'.

A Series is a single labelled column. A DataFrame is a table made of several Series that share an index. Selecting one column with df['name'] gives you a Series; selecting with a list, df[['name']], gives a one-column DataFrame.

Pandas warns when you assign into something that might be a copy of another table. Fix it by using a single loc assignment, or by calling .copy() when you really want an independent table.

Pandas holds data in memory, so the limit is your RAM. For files that are too big you can read in chunks, select only the columns you need, use smaller dtypes, or move to a database or a tool designed for larger-than-memory data. For most everyday files it is perfectly comfortable.

Use df.to_csv('file.csv', index=False) for a CSV that opens anywhere. Other writers such as to_json and to_excel exist, though Excel output needs an extra package. The CSV and JSON lesson covers the standard-library route.

Key takeaways

  • βœ“A Series is a labelled column and a DataFrame is a table of Series sharing an index; build them from dicts, lists or CSV text.
  • βœ“Use loc for labels, iloc for positions, and boolean masks (with parentheses and &, |) for filtering.
  • βœ“Count missing values with isna().sum() and decide deliberately whether to drop or fill them.
  • βœ“groupby with named agg is split-apply-combine in one readable statement; reset_index makes the keys columns again.
  • βœ“merge joins tables on keys (prefer how='left' to keep your main data) and pivot_table makes two-way summaries.
  • βœ“Use .str for text cleaning and to_datetime plus .dt for dates, and finish every analysis with a sanity check.