⚡0 XP🔥0

pandas Series and DataFrames

Lesson 2 of 7 ⏱ 4 min read ✎ 2 exercises ❓ 5-question quiz ▶ Runs Python

The two pandas data structures - Series and DataFrame - creating them, index and columns, selecting with [], loc and iloc, adding and removing columns, and vectorised calculations.

pandas in one sentence#

pandas gives Python an Excel-like table (the DataFrame) with powerful tools to load, clean, analyse and export data - for files with thousands or millions of rows.

import pandas as pd     # standard alias

Series - one column#

A Series is a one-dimensional labelled array (a single column with an index):

▶ Try it YourselfPython
Ctrl + Enter to run

DataFrame - a table#

A DataFrame is a 2D table: rows (with an index) and named columns. Each column is a Series.

▶ Try it YourselfPython
Ctrl + Enter to run
हिंदी में समझें

pandas में दो मुख्य चीज़ें हैं:

  • Series = एक column (जैसे सिर्फ sales वाला column), जिसके साथ labels (index) होते हैं।
  • DataFrame = पूरी table (कई columns), बिल्कुल Excel sheet जैसी।

DataFrame का हर column असल में एक Series है। Rows की पहचान index से होती है (default 0, 1, 2...)।

Selecting columns#

df["sales"]                 # one column → Series
df[["city", "sales"]]       # several columns → DataFrame (note the double brackets)
df.sales                    # attribute style - works if the name has no spaces

Selecting rows and cells: loc and iloc#

loc - by label iloc - by position
one row df.loc[2] df.iloc[2]
one cell df.loc[2, "city"] df.iloc[2, 0]
slice df.loc[1:3, "city":"sales"] (end included) df.iloc[1:3, 0:3] (end excluded)
condition df.loc[df["sales"] > 80000, ["city", "sales"]] -
▶ Try it YourselfPython
Ctrl + Enter to run

Setting a meaningful index#

▶ Try it YourselfPython
Ctrl + Enter to run

Filtering rows#

Boolean masks work exactly like NumPy:

▶ Try it YourselfPython
Ctrl + Enter to run

Adding, changing and removing columns#

▶ Try it YourselfPython
Ctrl + Enter to run
Tip

Calculations on whole columns (df["a"] / df["b"]) are vectorised - never loop over rows with for to calculate a column. It's slower and harder to read.

Sorting#

df.sort_values("sales", ascending=False)
df.sort_values(["region", "sales"], ascending=[True, False])
df.nlargest(3, "sales")        # top 3

Summary#

  • Series = one labelled column; DataFrame = a table of Series.
  • Select columns with df["col"] / df[["a", "b"]]; rows/cells with loc (labels) and iloc (positions).
  • Filter with boolean masks, isin, or query.
  • Create columns with vectorised expressions and np.where; rename, drop and sort easily.

Practice Exercises

Write your code, then press Check. Your program is tested automatically.

1

Build a DataFrame

Create a DataFrame df with columns student, maths, science from the lists given. Add a column total (maths + science) and a column result = "Pass" if total ≥ 100 else "Fail" (use np.where). Print df.

2

Select with loc

Using df below, create toppers - the student and total columns for students whose total is above 150 (use .loc with a condition).

Quick Quiz

Q1.

What is a pandas DataFrame?

Q2.

Which selects the column 'sales' as a Series?

Q3.

What is the difference between loc and iloc?

Q4.

How do you add a column 'margin' = profit / sales?

Q5.

Which returns a DataFrame with two columns?