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.
Make a DataFrame with columns item and price for three items and print the item with the highest price.
From the register example, print the average salary of people older than 25.
Add a column price_with_tax that is price times 1.2, and print the frame.
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
What is the difference between a Series and a DataFrame?
When do you use loc and when iloc? What is the difference in slice behaviour?
How do you filter rows by two conditions? What common mistakes appear?
Why does df[mask]["col"] = 0 not do what you want, and what is the fix?
Two Series with different index labels are added and most results are NaN. Why, and how do you get a sensible answer?
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