You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何按Type列分组DataFrame并合并列表类型列

Solution for Grouping DataFrame with List Columns by Type

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 the Type column.
  • lambda x: sum(x, []): This lambda takes each group of lists (for Components or Names) and chains them into one single list. Using sum(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 the Type index 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 07:04:37