1. Introduction to pandas
1.4 Pick columns and rows: [ ], loc and iloc
Highlights & notes
Select lesson text to highlight it, or tap Add note.
Bookmarks
Bookmark a lesson to see it here.
A DataFrame is a big table. Most of the time you need only a slice of it: one column, a few columns, or a few rows.
df["amount"]gives one column as a Seriesdf[["name", "amount"]]gives several columns as a smaller DataFrame. Note the double brackets: the inner pair is a list.df.iloc[0]gives a row by its positiondf.loc[1, "city"]gives one cell by row label and column name
iloc counts positions from 0 and leaves out the end: df.iloc[0:2] gives rows 0 and 1. loc uses labels and includes the end.
One column, then two
Single brackets for one column, double for several.
Python
import pandas as pddf = pd.DataFrame({ "name": ["Asha", "Ravi", "Meera", "Kabir"], "city": ["Noida", "Delhi", "Pune", "Noida"], "amount": [250, 400, 150, 90],})print(df["amount"])print(df[["name", "amount"]])
Output
0 250
1 400
2 150
3 90
Name: amount, dtype: int64
name amount
0 Asha 250
1 Ravi 400
2 Meera 150
3 Kabir 90
Quick check
Which one returns a DataFrame with two columns?
Rows and single cells
iloc uses positions. loc uses labels.
Python
import pandas as pddf = pd.DataFrame({ "name": ["Asha", "Ravi", "Meera", "Kabir"], "city": ["Noida", "Delhi", "Pune", "Noida"], "amount": [250, 400, 150, 90],})print(df.iloc[0])print(df.loc[1, "city"])print(df.iloc[0:2])
Output
name Asha city Noida amount 250 Name: 0, dtype: object Delhi name city amount 0 Asha Noida 250 1 Ravi Delhi 400
Quick check
How many rows does df.iloc[1:3] return?
Practice in pandas ✓ Solved
Print only the city and amount columns of df.
Expected output
city amount 0 Noida 250 1 Delhi 400 2 Pune 150 3 Noida 90
Reference solution
import pandas as pd
df = pd.DataFrame({
"name": ["Asha", "Ravi", "Meera", "Kabir"],
"city": ["Noida", "Delhi", "Pune", "Noida"],
"amount": [250, 400, 150, 90],
})
print(df[["city", "amount"]])
Question 1 · Easy
What does df["amount"] return?
Question 2 · Medium
Which reads the cell in row label 2 and column "name"?
Question 3 · Hard
Which rows does df.iloc[0:2] give?
Key takeaways
Use df["col"] for one column, df[["a", "b"]] for several, iloc for positions and loc for labels. iloc slices leave out the end.
Save your progress
Start free and your progress, code and notes stay saved. Free for 1 month, no card needed.
Start free Log in