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

Pandas多DataFrame合并去重:实现动物-颜色双向分组列表

处理多个同结构DataFrame的分组聚合需求

问题说明

现有多个结构相同的DataFrame,示例数据如下:

animal  color       animal color       animal color
0 dog     red       0 dog    blue      0 cat    green
1 cat     red       1 cat    blue      1 mouse  green
2 rat     red       2 horse  blue      2 seal   green
3 mouse   red       3 eagle  blue      3 bird   green

需要生成两种结果DataFrame:

  1. 按动物分组:每个唯一动物对应其所有出现过的颜色列表

animal color
0 dog ['red','blue']
1 cat ['red','blue','green']
2 rat ['red']
3 mouse ['red','green']
4 horse ['blue']
5 eagle ['blue']
6 seal ['green']
7 bird ['green']

2. 按颜色分组:每个唯一颜色对应其所有出现过的动物列表

color animals
0 red ['dog','cat','rat','mouse']
1 blue ['dog','cat','horse','eagle']
2 green ['cat','mouse','seal','bird']

要求分组后的值保留为列表格式,方便后续用`len()`统计数量。

## 解决方案
### 1. 合并所有DataFrame
先将所有结构相同的DataFrame合并成一个大的DataFrame,假设你的DataFrames存储在列表`dfs`中:
```python
import pandas as pd

# 假设dfs是包含所有目标DataFrame的列表
combined_df = pd.concat(dfs, ignore_index=True)

2. 生成按动物分组的结果

通过groupby分组后,使用agg将对应颜色聚合为列表:

# 直接聚合为列表(若存在重复颜色会保留重复值)
animal_color_df = combined_df.groupby('animal')['color'].agg(list).reset_index()

# 若需要去重且保留首次出现顺序
# animal_color_df = combined_df.groupby('animal')['color'].agg(lambda x: list(dict.fromkeys(x))).reset_index()

# 若不需要保留顺序,仅去重
# animal_color_df = combined_df.groupby('animal')['color'].agg(lambda x: list(set(x))).reset_index()

3. 生成按颜色分组的结果

同理,按颜色分组后聚合动物为列表:

# 直接聚合为列表(若存在重复动物会保留重复值)
color_animal_df = combined_df.groupby('color')['animal'].agg(list).reset_index()

# 若需要去重且保留首次出现顺序
# color_animal_df = combined_df.groupby('color')['animal'].agg(lambda x: list(dict.fromkeys(x))).reset_index()

# 若不需要保留顺序,仅去重
# color_animal_df = combined_df.groupby('color')['animal'].agg(lambda x: list(set(x))).reset_index()

内容的提问来源于stack exchange,提问作者Gerardo Morales

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.10 05:52:50