We use cookies (including Google cookies) to personalize ads and analyze traffic. By continuing to use our site, you accept our Privacy Policy.

Change Data Type

Difficulty: Easy


Problem Description

The grade column in the students DataFrame is stored as floats. Your task is to convert this column to integers.


Key Insights

  • The grade column data type needs to be changed from float to int.
  • Conversion should be straightforward since float values can be cast to integers.
  • Ensure that the output DataFrame maintains the original structure apart from the data type change.

Space and Time Complexity

Time Complexity: O(n), where n is the number of records in the DataFrame, since we need to process each entry in the grade column.

Space Complexity: O(1), as we are modifying the existing DataFrame in place without needing additional data structures.


Solution

To solve the problem, we need to access the grade column of the students DataFrame and convert its data type from float to integer. This can be achieved using built-in methods available in DataFrame manipulation libraries (like pandas in Python). The conversion will not change the number of rows or other columns in the DataFrame, ensuring the output format remains consistent.


Code Solutions

import pandas as pd

# Sample DataFrame creation
students = pd.DataFrame({
    'student_id': [1, 2],
    'name': ['Ava', 'Kate'],
    'age': [6, 15],
    'grade': [73.0, 87.0]
})

# Convert the 'grade' column from float to int
students['grade'] = students['grade'].astype(int)

# Display the updated DataFrame
print(students)
← Back to All Questions