Command Palette

Search for a command to run...

Hectal
Back to the lesson: Topic 14.6 — pandas: Series and DataFrames
Python · Example 2 of 4

Select, filter and add columns

Change Pune to Delhi in the filter. Then add a third condition with & and brackets.

pandas gives Python tables: a DataFrame is a table with labelled columns and rows, and a Series is one column. You select with [], loc and iloc, filter with boolean masks and add columns by assignment.

Change the code and press Run (Ctrl+Enter). Predict what will happen first, then break it on purpose and read what changes. Your edits are saved and match the lesson page.

Ready for more? This phase has 6 hands-on exercises with automatic checks.

Practice questions

Write the code in the editor, run it, then open the model answer to compare.

01

Make a DataFrame with columns item and price for three items and print the item with the highest price.

02

From the register example, print the average salary of people older than 25.

03

Add a column price_with_tax that is price times 1.2, and print the frame.

04

Give every person from Pune a raise of 5000 in place, with a single loc assignment, and print the frame. Start from city = Pune, Delhi, Pune and salary = 52000.0, 71000.0, 64000.5.

Explain it without notes

01

What is the difference between a Series and a DataFrame?

02

When do you use loc and when iloc? What is the difference in slice behaviour?

03

How do you filter rows by two conditions? What common mistakes appear?

04

Why does df[mask]["col"] = 0 not do what you want, and what is the fix?

05

Two Series with different index labels are added and most results are NaN. Why, and how do you get a sensible answer?

Select, filter and add columns
Sign in to run this example in your browser.

Expected output

['Asha', 'Ben', 'Chen', 'Dia']
    name    city
r1  Asha    Pune
r2   Ben   Delhi
r3  Chen    Pune
r4   Dia  Mumbai
loc row: Ben
iloc row 2, name: Chen | first two cells: Chen 27
loc slice: [23, 31]
    name  age  city   salary
r1  Asha   23  Pune  52000.0
r3  Chen   27  Pune  64000.5
['Ben', 'Chen', 'Dia']
    name    bonus  senior
r1  Asha  5200.00   False
r2   Ben  7100.00    True
r3  Chen  6400.05   False
r4   Dia  9000.00    True