Recall & Review
beginner
How do you select a single column named 'Age' from a pandas DataFrame?
Use
df['Age'] to select the column named 'Age' from the DataFrame df. This returns a Series with the data from that column.Click to reveal answer
beginner
How can you select multiple columns, for example 'Name' and 'Age', from a pandas DataFrame?
Use
df[['Name', 'Age']] to select multiple columns. This returns a new DataFrame with only those columns.Click to reveal answer
beginner
What happens if you try to select a column name that does not exist in the DataFrame?
pandas will raise a
KeyError because the column name is not found in the DataFrame.Click to reveal answer
intermediate
How do you select columns by name using the
.loc accessor?Use
df.loc[:, ['Name', 'Age']] to select columns by name. The colon : means select all rows, and the list specifies the columns.Click to reveal answer
intermediate
Can you select columns by name using dot notation like
df.Age? When is this recommended?Yes, you can use
df.Age to select a column named 'Age'. However, this works only if the column name is a valid Python identifier and does not conflict with DataFrame methods. It's safer to use df['Age'].Click to reveal answer
Which syntax selects the column 'Salary' from DataFrame
df?✗ Incorrect
Use
df['Salary'] to select a single column by name.How do you select columns 'Name' and 'Department' together?
✗ Incorrect
Use a list inside double brackets:
df[['Name', 'Department']].What does
df.loc[:, ['Age', 'Salary']] do?✗ Incorrect
The colon means all rows, and the list selects the columns.
What error occurs if you select a non-existing column like
df['Height']?✗ Incorrect
pandas raises a
KeyError if the column is missing.Which is the safest way to select a column named 'class'?
✗ Incorrect
Use
df['class'] because 'class' is a Python keyword and dot notation may fail.Explain how to select one or more columns by name from a pandas DataFrame.
Think about single vs multiple columns and the loc accessor.
You got /3 concepts.
What are the risks or errors when selecting columns by name, and how can you avoid them?
Consider what happens if the column name is missing or unusual.
You got /3 concepts.