Home >Web Front-end >JS Tutorial >How can Python's `groupby` method efficiently group and aggregate data from arrays of objects?
Grouping Objects in Arrays Using GroupBy Method
Python's powerful groupby method enables efficient grouping of objects based on selected attributes. If you need to perform such grouping operations, groupby offers a convenient solution.
For instance, consider the following array of objects:
[ { Phase: "Phase 1", Step: "Step 1", Task: "Task 1", Value: "5" }, { Phase: "Phase 1", Step: "Step 1", Task: "Task 2", Value: "10" }, { Phase: "Phase 1", Step: "Step 2", Task: "Task 1", Value: "15" }, { Phase: "Phase 1", Step: "Step 2", Task: "Task 2", Value: "20" }, { Phase: "Phase 2", Step: "Step 1", Task: "Task 1", Value: "25" }, { Phase: "Phase 2", Step: "Step 1", Task: "Task 2", Value: "30" }, { Phase: "Phase 2", Step: "Step 2", Task: "Task 1", Value: "35" }, { Phase: "Phase 2", Step: "Step 2", Task: "Task 2", Value: "40" } ]
To group the objects by Phase and calculate the sum of Value, we use:
from itertools import groupby def sum_value(objects): return sum(int(obj["Value"]) for obj in objects) objects.sort(key=lambda obj: obj["Phase"]) grouped_by_phase = groupby(objects, key=lambda obj: obj["Phase"]) result = [{ "Phase": phase, "Value": sum_value(objects) } for phase, objects in grouped_by_phase] print(result)
This yields the desired output:
[{"Phase": "Phase 1", "Value": 50}, {"Phase": "Phase 2", "Value": 130}]
Alternatively, to group by both Phase and Step, we can use multiple levels of groupby:
grouped_by_phase_and_step = groupby(objects, key=lambda obj: (obj["Phase"], obj["Step"])) result = [{ "Phase": phase, "Step": step, "Value": sum_value(objects) } for (phase, step), objects in grouped_by_phase_and_step] print(result)
This returns:
[{"Phase": "Phase 1", "Step": "Step 1", "Value": 15}, {"Phase": "Phase 1", "Step": "Step 2", "Value": 35}, {"Phase": "Phase 2", "Step": "Step 1", "Value": 55}, {"Phase": "Phase 2", "Step": "Step 2", "Value": 75}]
With Python's versatile groupby method, you can easily and efficiently group and aggregate data from arrays of objects, meeting your various grouping requirements.
The above is the detailed content of How can Python's `groupby` method efficiently group and aggregate data from arrays of objects?. For more information, please follow other related articles on the PHP Chinese website!