Problem#
DataFrame students
+-------------+--------+
| Column Name | Type |
+-------------+--------+
| id | int |
| first | object |
| last | object |
| age | int |
+-------------+--------+
Write a solution to rename the columns as follows:
id
to student_id
first
to first_name
last
to last_name
age
to age_in_years
The result format is in the following example.
### Examples
Example 1#
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
|
Input: +----+---------+----------+-----+
| id | first | last | age |
+----+---------+----------+-----+
| 1 | Mason | King | 6 |
| 2 | Ava | Wright | 7 |
| 3 | Taylor | Hall | 16 |
| 4 | Georgia | Thompson | 18 |
| 5 | Thomas | Moore | 10 |
+----+---------+----------+-----+
Output:
+------------+------------+-----------+--------------+
| student_id | first_name | last_name | age_in_years |
+------------+------------+-----------+--------------+
| 1 | Mason | King | 6 |
| 2 | Ava | Wright | 7 |
| 3 | Taylor | Hall | 16 |
| 4 | Georgia | Thompson | 18 |
| 5 | Thomas | Moore | 10 |
+------------+------------+-----------+--------------+
Explanation:
The column names are changed accordingly.
## Solution
### Method 1 -
### Method 1 - DataFrame.rename()
#### Intuition
We need to rename columns in a pandas DataFrame. The `rename` method allows us to map old column names to new ones easily.
#### Approach
Use the `rename` method with a dictionary mapping old names to new names, and set `axis=1` or `columns=`.
#### Code
##### Python (pandas)
```python
# students is a pandas DataFrame
students = students.rename(columns={
'id': 'student_id',
'first': 'first_name',
'last': 'last_name',
'age': 'age_in_years'
})
|
Complexity#
- ⏰ Time complexity: O(N), where N is the number of columns (constant here).
- 🧺 Space complexity: O(1), as the operation is in-place or returns a new DataFrame with the same data.