0
0
Pandasdata~5 mins

Selecting columns by name in Pandas - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
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?
Adf['Salary', 'Age']
Bdf.Salary()
Cdf.loc['Salary']
Ddf['Salary']
How do you select columns 'Name' and 'Department' together?
Adf[['Name', 'Department']]
Bdf.Name.Department
Cdf.loc['Name', 'Department']
Ddf['Name', 'Department']
What does df.loc[:, ['Age', 'Salary']] do?
ASelects all rows and columns 'Age' and 'Salary'
BSelects rows 'Age' and 'Salary'
CSelects columns 'Age' and 'Salary' only for first row
DRaises an error
What error occurs if you select a non-existing column like df['Height']?
AValueError
BTypeError
CKeyError
DIndexError
Which is the safest way to select a column named 'class'?
Adf.class
Bdf['class']
Cdf.loc['class']
Ddf.class()
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.