Problem

DataFrame students

1
2
3
4
5
6
7
8
+-------------+--------+
| Column Name | Type |
+-------------+--------+
| student_id | int |
| name | object |
| age | int |
| grade | float |
+-------------+--------+

Write a solution to correct the errors:

The grade column is stored as floats, convert it to integers.

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
Input: DataFrame students:
+------------+------+-----+-------+
| student_id | name | age | grade |
+------------+------+-----+-------+
| 1          | Ava  | 6   | 73.0  |
| 2          | Kate | 15  | 87.0  |
+------------+------+-----+-------+
Output: +------------+------+-----+-------+
| student_id | name | age | grade |
+------------+------+-----+-------+
| 1          | Ava  | 6   | 73    |
| 2          | Kate | 15  | 87    |
+------------+------+-----+-------+
Explanation: 
The data types of the column grade is converted to int.

Solution

Method 1 – Pandas astype Conversion

Intuition: The task is to convert the ‘grade’ column from float to int. This is a direct use of pandas’ type conversion capabilities.

Approach:

  1. Use the astype(int) method on the ‘grade’ column to convert its type from float to int.
  2. Return the modified DataFrame.

Code

1
2
3
4
5
import pandas as pd

def changeDataType(students: pd.DataFrame) -> pd.DataFrame:
    students['grade'] = students['grade'].astype(int)
    return students

Complexity

  • ⏰ Time complexity: O(n), where n is the number of rows.
  • 🧺 Space complexity: O(1) extra (in-place conversion).