Practical map() Examples
Data Cleaning and Preprocessing
Handling Numeric Data
## Cleaning and normalizing numeric data
raw_data = ['10.5', '20.3', '30.7', '40.2']
cleaned_data = list(map(float, raw_data))
normalized_data = list(map(lambda x: round(x, 2), cleaned_data))
print(normalized_data) ## Output: [10.5, 20.3, 30.7, 40.2]
Scientific Computing
Vector Operations
## Performing element-wise mathematical operations
def celsius_to_fahrenheit(temp):
return (temp * 9/5) + 32
temperatures = [0, 10, 20, 30]
fahrenheit_temps = list(map(celsius_to_fahrenheit, temperatures))
print(fahrenheit_temps) ## Output: [32.0, 50.0, 68.0, 86.0]
Web Development and Data Processing
## Transforming JSON-like data structures
users = [
{'name': 'Alice', 'age': 25},
{'name': 'Bob', 'age': 30}
]
user_names = list(map(lambda user: user['name'], users))
print(user_names) ## Output: ['Alice', 'Bob']
Machine Learning Preprocessing
Feature Scaling
## Scaling numeric features
def min_max_scaling(x, min_val, max_val):
return (x - min_val) / (max_val - min_val)
data = [10, 20, 30, 40, 50]
scaled_data = list(map(lambda x: min_max_scaling(x, min(data), max(data)), data))
print(scaled_data) ## Output: [0.0, 0.25, 0.5, 0.75, 1.0]
Practical Mapping Scenarios
Scenario |
Technique |
Benefit |
Data Cleaning |
Numeric Conversion |
Standardize input |
Temperature Conversion |
Mathematical Mapping |
Unit transformation |
JSON Processing |
Selective Extraction |
Data restructuring |
Feature Engineering |
Scaling Functions |
Normalize data |
Mapping Strategy Visualization
graph TD
A[Raw Data] --> B{map() Function}
B --> C[Cleaned Data]
B --> D[Transformed Data]
B --> E[Processed Data]
Best Practices
- Use
map()
for uniform transformations
- Combine with
lambda
for complex operations
- Consider list comprehensions for simple cases
- Profile performance for large datasets
By exploring these practical examples, LabEx learners can effectively leverage map()
in real-world scenarios.