如何按Type列分组DataFrame并合并列表类型列
Got it, let's sort out this grouping problem you're facing. The key here is that standard groupby operations don't handle list concatenation out of the box—we need to use a custom aggregation function to combine those lists properly.
First, let's recreate your sample DataFrame to test with:
import pandas as pd data = { 'Type': ['Zebra', 'Zebra', 'Zebra', 'Lion', 'Tiger'], 'Components': [['hand','arm','nose'], ['eyes','fingers'], ['paws'], ['teeth'], ['fingers']], 'Names': [['bubu','kuku'], ['gaga','timber'], [], ['scar'], ['figgy']] } df = pd.DataFrame(data)
The Fix: Custom Aggregation with groupby + agg
To group by the Type column and concatenate the list values in Components and Names, we'll use groupby followed by agg() with a lambda function that sums the lists (using an empty list as the initial value to handle empty entries smoothly):
grouped_df = df.groupby('Type').agg({ 'Components': lambda x: sum(x, []), 'Names': lambda x: sum(x, []) }).reset_index()
Let's break this down:
groupby('Type'): Groups the DataFrame rows by the unique values in theTypecolumn.lambda x: sum(x, []): This lambda takes each group of lists (forComponentsorNames) and chains them into one single list. Usingsum(x, [])works because summing lists with an empty list as the starting point effectively concatenates all sublists. Empty lists in the groups won't add anything to the final result, which matches your desired output.reset_index(): Moves theTypeindex back to a regular column, so the output structure matches what you're looking for.
Final Result
Running this code will give you exactly the output you want:
Type Components Names 0 Zebra [hand, arm, nose, eyes, fingers, paws] [bubu, kuku, gaga, timber] 1 Lion [teeth] [scar] 2 Tiger [fingers] [figgy]
Quick note on why your initial attempt failed: Standard aggregation functions (like the default sum) are built for numeric data, not lists. We need to explicitly tell pandas how to combine the list values with a custom function.
内容的提问来源于stack exchange,提问作者Jeremy Hunts

