Convert Boolean Values Practice Problem
This data science coding problem helps you practice Data Type Conversion & Validation, convert boolean values, and implementation skills. Read the problem statement, write your solution, and strengthen your understanding of Data Type Conversion & Validation.
- Problem ID: 39
- Problem key: 39-convert-boolean-values
- URL: https://datacrack.app/solve/39-convert-boolean-values
- Difficulty: easy
- Topic: Data Type Conversion & Validation
- Module: Data Cleaning
Problem Statement
# Convert Boolean Values
### 🎯 Goal
Convert common string representations of boolean values into actual Python booleans.
### 💻 Task
Implement `convert_booleans(data, column)` that:
1. Converts the input dictionary to a DataFrame
2. Maps common boolean string representations to Python `True`/`False`
3. Handles case-insensitive matching for: `"Yes"/"No"`, `"True"/"False"`, `"T"/"F"`, `"1"/"0"`, `"Y"/"N"`
4. Returns the resulting DataFrame
---
### 📥 Input
- `data`: A dictionary where keys are column names and values are lists of boolean-like strings
- `column`: The name of the column to convert
### 📤 Output
- A pandas DataFrame with the specified column converted to Python booleans
---
### 🧩 Starter Code
```python
import pandas as pd
import numpy as np
def convert_booleans(data, column):
"""
Convert common boolean string representations to Python booleans.
Args:
data (dict): Input data as dictionary with boolean-like strings
column (str): Name of the column to convert
Returns:
pd.DataFrame: DataFrame with the column converted to booleans
"""
# TODO: Convert the input dictionary to a DataFrame
# TODO: Define a mapping of common boolean string representations
# TODO: Apply the mapping (case-insensitive) to the specified column
# TODO: Return the resulting DataFrame
pass
```
---
### 💡 Examples
**Example 1:** Yes/No values
```python
data = {"active": ["Yes", "No", "Yes", "No"]}
convert_booleans(data, "active")
```
```
active
0 True
1 False
2 True
3 False
```
**Example 2:** T/F shorthand
```python
data = {"flag": ["T", "F", "T", "F", "T"]}
convert_booleans(data, "flag")
```
```
flag
0 True
1 False
2 True
3 False
4 True
```
**Example 3:** Numeric 1/0 strings
```python
data = {"status": ["1", "0", "1", "1", "0"]}
convert_booleans(data, "status")
```
```
status
0 True
1 False
2 True
3 True
4 False
```Starter Code
import pandas as pd
import numpy as np
def convert_booleans(data, column):
"""
Convert common boolean string representations to Python booleans.
Args:
data (dict): Input data as dictionary with boolean-like strings
column (str): Name of the column to convert
Returns:
pd.DataFrame: DataFrame with the column converted to booleans
"""
# TODO: Convert the input dictionary to a DataFrame
# TODO: Define a mapping of common boolean string representations
# TODO: Apply the mapping (case-insensitive) to the specified column
# TODO: Return the resulting DataFrame
pass