Back to blog
Oct 14, 2024
2 min read

Change Data Type

Convert a value from one data type to another, handling edge cases.

Difficulty: Easy | Acceptance: 87.30% | Paid: No Topics: N/A

Change Data Type

Write a solution to change the data type of a value from one type to another.

Examples

Example 1

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.

Constraints

- The input value will be a valid representation of the target type.
- For integer conversions, handle truncation of decimal parts.
- For string to number conversions, the string will contain only valid numeric characters.

Table of Contents


Direct Type Conversion

Intuition Use language-specific type casting or conversion operators to directly convert between types.

Steps

  • Identify the source and target types
  • Apply the appropriate conversion operator or function
  • Handle any potential exceptions or edge cases
def change_data_type(value, target_type):
    if target_type == 'int':
        return int(value)
    elif target_type == 'float':
        return float(value)
    elif target_type == 'str':
        return str(value)
    elif target_type == 'bool':
        return bool(value)
    else:
        raise ValueError(f"Unsupported target type: {target_type}")

Complexity

  • Time: O(1) for basic type conversions
  • Space: O(1) additional space
  • Notes: Direct conversion is the most efficient method for simple type changes.