2886 Change Data Type

Problem Statement

DataFrame students

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.

For the whole problem statement, please refer here.

Plans

  • Import pandas to manipulate the DataFrame.

  • Create a function named changeDatatype that takes a DataFrame as input.

  • Use astype(int) to convert the grade column from float to int.

  • Ensure the modified DataFrame is returned as the output.

Solution

import pandas as pd

def changeDatatype(students: pd.DataFrame) -> pd.DataFrame:
    # Change the data type of the 'grade' column to int
    students['grade'] = students['grade'].astype(int)

    # Change the data type of the 'age' column to int
    return students

Explanation

  1. Import Pandas

    • We start by importing the Pandas library, which provides data structures and operations for manipulating numerical tables and time series.

  2. Define the Function

    • We define a function changeDatatype that takes a single argument students, which is a DataFrame containing student data.

  3. Changing Data Type

    • We use the astype(int) method on the grade column of the DataFrame students to convert the data type from float to int.

  4. Return the Result

    • We return the modified DataFrame after changing the data type of the grade column to int.

Last updated