Change Data Type - Problem
You're working as a data analyst and have received a student dataset with a critical data type error! ๐
The DataFrame contains student information where the grade column is incorrectly stored as float values, but grades should be represented as integers for proper analysis and reporting.
Your task: Convert the grade column from float to integer data type while preserving all other columns unchanged.
| Column Name | Current Type | Expected Type |
|---|---|---|
| student_id | int | int โ |
| name | object | object โ |
| age | int | int โ |
| grade | float โ | int ๐ฏ |
Note: This is a common data preprocessing step in pandas that ensures data consistency and proper analysis.
Input & Output
example_1.py โ Basic Grade Conversion
$
Input:
DataFrame:
student_id | name | age | grade
1 | Alice | 20 | 85.0
2 | Bob | 21 | 92.0
3 | Charlie | 19 | 78.0
โบ
Output:
DataFrame:
student_id | name | age | grade
1 | Alice | 20 | 85
2 | Bob | 21 | 92
3 | Charlie | 19 | 78
Data types: grade column changed from float64 to int64
๐ก Note:
All grade values (85.0, 92.0, 78.0) are successfully converted to integers (85, 92, 78) while preserving other columns
example_2.py โ Single Student Record
$
Input:
DataFrame:
student_id | name | age | grade
100 | Emma | 22 | 95.0
โบ
Output:
DataFrame:
student_id | name | age | grade
100 | Emma | 22 | 95
Data types: grade column changed from float64 to int64
๐ก Note:
Even with a single record, the conversion works correctly, changing 95.0 to 95
example_3.py โ Edge Case with Whole Number Floats
$
Input:
DataFrame:
student_id | name | age | grade
1 | Alex | 19 | 88.0
2 | Sarah | 20 | 100.0
3 | Mike | 21 | 75.0
โบ
Output:
DataFrame:
student_id | name | age | grade
1 | Alex | 19 | 88
2 | Sarah | 20 | 100
3 | Mike | 21 | 75
Data types: grade column changed from float64 to int64
๐ก Note:
All grades are whole numbers stored as floats, conversion preserves the numeric values perfectly
Visualization
Tap to expand
Understanding the Visualization
1
Identify Column
Locate the 'grade' column with float64 data type
2
Apply Conversion
Use pandas astype(int) for vectorized conversion
3
Verify Result
Confirm grade column is now int64 type
Key Takeaway
๐ฏ Key Insight: Use pandas' built-in `astype()` method for efficient, vectorized data type conversions instead of manual row-by-row processing
Time & Space Complexity
Time Complexity
O(n)
Must iterate through each of the n rows to convert grades individually
โ Linear Growth
Space Complexity
O(1)
Only modifying existing DataFrame in-place, no additional data structures needed
โ Linear Space
Constraints
- 1 โค number of students โค 104
- All grade values are valid whole numbers stored as floats
- Grade values range from 0.0 to 100.0
- DataFrame structure must remain unchanged except for grade column data type
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code