Data transformation is a critical process of converting filtered data into desired formats or structures, enabling more advanced data manipulation and analysis.
The map()
function allows applying a function to each filtered element:
## Transforming filtered data
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
squared_even_numbers = list(map(lambda x: x**2, filter(lambda x: x % 2 == 0, numbers)))
print(squared_even_numbers) ## Output: [4, 16, 36, 64, 100]
List comprehensions provide a more concise transformation approach:
## Comprehensive transformation
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
squared_even_numbers = [x**2 for x in numbers if x % 2 == 0]
print(squared_even_numbers) ## Output: [4, 16, 36, 64, 100]
graph TD
A[Data Transformation] --> B[Filtering]
A --> C[Mapping]
A --> D[Reducing]
B --> E[Conditional Selection]
C --> F[Element Modification]
D --> G[Aggregation]
## Dictionary transformation
students = [
{'name': 'Alice', 'grade': 85},
{'name': 'Bob', 'grade': 92},
{'name': 'Charlie', 'grade': 78}
]
high_performers = {
student['name']: student['grade'] * 1.1
for student in students if student['grade'] >= 80
}
print(high_performers)
Method |
Flexibility |
Performance |
Readability |
map() |
Moderate |
Good |
Moderate |
List Comprehension |
High |
Excellent |
High |
Generator Expressions |
Excellent |
Memory Efficient |
Moderate |
- Lambda functions for inline transformations
- Applying multiple transformations sequentially
- Combining filtering and mapping
- Use generator expressions for large datasets
- Minimize complex transformation logic
- Prefer list comprehensions for simple transformations
LabEx Learning Tip
LabEx recommends practicing these transformation techniques through interactive coding exercises to build practical skills.