0
0
Pandasdata~5 mins

loc for label-based selection in Pandas - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
Recall & Review
beginner
What does the loc function in pandas do?

loc is used to select rows and columns by their labels (names) in a DataFrame.

Click to reveal answer
beginner
How do you select a single row with label 'A' using loc?

You use df.loc['A'] to get the row labeled 'A'.

Click to reveal answer
intermediate
How to select multiple rows labeled 'A' and 'B' and columns 'X' and 'Y' using loc?

Use df.loc[['A', 'B'], ['X', 'Y']] to select those rows and columns by label.

Click to reveal answer
intermediate
What happens if you use loc with a label that does not exist?

It raises a KeyError because the label is not found in the DataFrame index or columns.

Click to reveal answer
intermediate
Can loc select rows using a label range like 'A' to 'C'?

Yes, loc supports label slicing, so df.loc['A':'C'] selects rows from 'A' to 'C' inclusive.

Click to reveal answer
What does df.loc['row1'] return?
AThe first row by position
BThe column named 'row1'
CThe row with label 'row1'
DAn error
How do you select columns 'A' and 'B' for rows labeled 'x' and 'y'?
Adf.loc['A':'B', 'x':'y']
Bdf.loc[['x', 'y'], ['A', 'B']]
Cdf.iloc[['x', 'y'], ['A', 'B']]
Ddf.iloc[0:2, 0:2]
What error occurs if you use loc with a missing label?
AKeyError
BIndexError
CValueError
DTypeError
Which of these selects rows from label 'a' to 'c' inclusive?
Adf.iloc[0:3]
Bdf.iloc['a':'c']
Cdf.loc['a','c']
Ddf.loc['a':'c']
What does df.loc[:, 'col1'] select?
AAll rows for column 'col1'
BAll columns for row 'col1'
COnly the first row
DOnly the first column
Explain how to use loc to select specific rows and columns by their labels in a pandas DataFrame.
Think about how you pick items by name in a list or dictionary.
You got /4 concepts.
    Describe what happens if you try to select a label that does not exist using loc.
    What happens when you ask for a key that is not in a dictionary?
    You got /3 concepts.