Difficulty: Easy | Acceptance: 78.50% | Paid: No Topics: N/A
DataFrame students +-------------+--------+ | Column Name | Type | +-------------+--------+ | student_id | int | | name | object | | age | int | +-------------+--------+ Write a solution to select the name and age of the student.
The result format is in the following example.
- Examples
- Constraints
- Direct Column Selection
- Using loc Accessor
- Using filter Method
Examples
Example 1:
Input:
+------------+---------+-----+
| student_id | name | age |
+------------+---------+-----+
| 1 | Alice | 20 |
| 2 | Bob | 21 |
| 3 | Charlie | 22 |
+------------+---------+-----+
Output:
+---------+-----+
| name | age |
+---------+-----+
| Alice | 20 |
| Bob | 21 |
| Charlie | 22 |
+---------+-----+
Constraints
The DataFrame students contains columns student_id, name, and age.
Direct Column Selection
Intuition
The most straightforward way to select specific columns in Pandas is by passing a list of column names to the indexing operator []. This returns a new DataFrame containing only the specified columns in the order they appear in the list.
Steps
- Access the DataFrame using the list of desired column names
['name', 'age']. - Return the resulting DataFrame.
import pandas as pd
def selectData(students: pd.DataFrame) -> pd.DataFrame:
return students[['name', 'age']]Complexity
- Time: O(n) where n is the number of rows.
- Space: O(n) to store the resulting DataFrame.
- Notes: This is the most idiomatic and concise way to select columns in Pandas.
Using loc Accessor
Intuition
The .loc accessor is primarily label-based, but can also be used with boolean arrays. It allows selecting rows and columns by label. Here we select all rows (:) and specific columns by their labels.
Steps
- Use
.locwith a slice:to select all rows. - Pass the list of column names
['name', 'age']to select specific columns. - Return the result.
import pandas as pd
def selectData(students: pd.DataFrame) -> pd.DataFrame:
return students.loc[:, ['name', 'age']]Complexity
- Time: O(n)
- Space: O(n)
- Notes: Useful when mixing row and column selection logic, though slightly more verbose than direct indexing for simple column selection.
Using filter Method
Intuition
The filter method in Pandas allows selecting subsets of the DataFrame based on labels (either row index or column names). It is particularly useful if you want to select columns based on a pattern or regex, but works with exact names too.
Steps
- Call the
filtermethod on the DataFrame. - Use the
itemsparameter (orlike/regex) with the list['name', 'age']. - Return the result.
import pandas as pd
def selectData(students: pd.DataFrame) -> pd.DataFrame:
return students.filter(items=['name', 'age'])Complexity
- Time: O(n)
- Space: O(n)
- Notes: Overkill for simple selection but very powerful for selecting columns matching patterns (e.g.,
like='name').