Data transformation is a crucial process in data analysis and processing, where lambda functions play a significant role in efficiently manipulating and converting data.
graph TD
A[Data Transformation] --> B[Mapping]
A --> C[Filtering]
A --> D[Aggregation]
A --> E[Normalization]
1. Mapping Data
## Transform a list of temperatures from Celsius to Fahrenheit
celsius_temps = [0, 10, 20, 30, 40]
fahrenheit_temps = list(map(lambda x: (x * 9/5) + 32, celsius_temps))
print(fahrenheit_temps)
## Output: [32.0, 50.0, 68.0, 86.0, 104.0]
2. Filtering Data
## Filter out specific data points
products = [
{'name': 'Laptop', 'price': 1200},
{'name': 'Smartphone', 'price': 800},
{'name': 'Tablet', 'price': 300}
]
expensive_products = list(filter(lambda x: x['price'] > 500, products))
print(expensive_products)
## Output: [{'name': 'Laptop', 'price': 1200}, {'name': 'Smartphone', 'price': 800}]
3. Data Normalization
## Normalize numeric data using lambda
raw_scores = [10, 20, 30, 40, 50]
max_score = max(raw_scores)
normalized_scores = list(map(lambda x: x / max_score, raw_scores))
print(normalized_scores)
## Output: [0.2, 0.4, 0.6, 0.8, 1.0]
## Complex data transformation
data = [
{'name': 'Alice', 'grades': [85, 90, 92]},
{'name': 'Bob', 'grades': [75, 80, 85]}
]
## Calculate average grades using nested lambda
avg_grades = list(map(lambda student: {
'name': student['name'],
'average': sum(student['grades']) / len(student['grades'])
}, data))
print(avg_grades)
## Output: [{'name': 'Alice', 'average': 89.0}, {'name': 'Bob', 'average': 80.0}]
Technique |
Pros |
Cons |
Lambda Mapping |
Fast |
Limited complexity |
List Comprehension |
Readable |
Slightly slower |
Pandas Transformation |
Powerful |
Overhead for small datasets |
Best Practices
- Use lambda for simple, one-line transformations
- Consider readability and performance
- Combine with
map()
, filter()
, and other functional programming tools
LabEx Recommendation
LabEx provides interactive Python environments to practice and master data transformation techniques with lambda functions.