Command Palette

Search for a command to run...

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

Assign safely with loc

The first frame stays unchanged after the filtered copy is edited with a copy; the second uses loc.

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?

Assign safely with loc
Sign in to run this example in your browser.

Expected output

original after editing a copy:
   a  b
0  1  4
1  2  5
2  3  6
   a  b
0  1  4
1  2  0
2  3  0