Make your choice

Renombrar Columnas

Escribe una solución para renombrar las columas como se muestra a continuación: id -> student_id first -> first_name last -> last_name age -> age_in_years

#pandas#data-cleaning#introduction-to-pandas
DataFrame students
+-------------+--------+
| Column Name | Type   |
+-------------+--------+
| id          | int    |
| first       | object |
| last        | object |
| age         | int    |
+-------------+--------+

El formato del resultado se muestra en el siguiente ejemplo.

Ejemplo 1:

Entrada:

+----+---------+----------+-----+
| id | first   | last     | age |
+----+---------+----------+-----+
| 1  | Mason   | King     | 6   |
| 2  | Ava     | Wright   | 7   |
| 3  | Taylor  | Hall     | 16  |
| 4  | Georgia | Thompson | 18  |
| 5  | Thomas  | Moore    | 10  |
+----+---------+----------+-----+

Salida:

+------------+------------+-----------+--------------+
| 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           |
+------------+------------+-----------+--------------+

Explicación:
Los nombres de las columnas se cambian de acuerdo a lo solicitado.

Solución

import pandas as pd


def renameColumns(students: pd.DataFrame) -> pd.DataFrame:
    new_names = {
        'id': 'student_id',
        'first': 'first_name',
        'last': 'last_name',
        'age': 'age_in_years',
    }
    return students.rename(columns=new_names)

slackmart blog © 2024