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

如何基于映射字典重组Pandas DataFrame?

问题:将Pandas DataFrame指定列合并为每行的字典列

我有一个Pandas DataFrame:

import pandas as pd

df = pd.DataFrame({'id': [11, 22],
 'name': ['foo', 'bar'],
 'class': ['c1', 'c2'],
 'date': ['01/07/2023', '14/05/2023'],
 'type': ['t1', 't2'],
 'attribute': ['a1', 'a2']})

原始DataFrame输出:

id name class        date type attribute
0  11  foo    c1  01/07/2023   t1        a1
1  22  bar    c2  14/05/2023   t2        a2

还有一个映射字典:

mapper = {
    "infos": ["name", "date"],
    "meta": ["class", "type", "attribute"]
}

期望得到的输出DataFrame:

id                                  infos                                              meta
0  11  {"name": "foo", "date": "01/07/2023"}  {"class": "c1", "type": "t1", "attribute": "a1"}
1  22  {"name": "bar", "date": "14/05/2023"}  {"class": "c2", "type": "t2", "attribute": "a2"}

我尝试了以下代码,但方向不对:

df[mapper["infos"]].apply(lambda x: {x.name: x.tolist()})

得到的结果是:

name                  {'name': ['foo', 'bar']}
date    {'date': ['01/07/2023', '14/05/2023']}

解决方案

要实现需求,核心是对每行的指定列生成字典,而不是按列处理。以下是两种可行方法:

方法1:使用apply(axis=1)逐行处理

通过指定axis=1参数,让apply按行遍历,将每行的目标列转为字典:

# 保留id列作为基础
result = df[['id']].copy()

# 生成infos列:每行的name和date转为字典
result['infos'] = df[mapper['infos']].apply(lambda row: row.to_dict(), axis=1)

# 生成meta列:每行的class、type、attribute转为字典
result['meta'] = df[mapper['meta']].apply(lambda row: row.to_dict(), axis=1)

print(result)

输出结果完全符合预期:

id                                  infos                                              meta
0  11  {'name': 'foo', 'date': '01/07/2023'}  {'class': 'c1', 'type': 't1', 'attribute': 'a1'}
1  22  {'name': 'bar', 'date': '14/05/2023'}  {'class': 'c2', 'type': 't2', 'attribute': 'a2'}

方法2:高效批量处理(适合大数据集)

如果DataFrame行数较多,逐行apply效率偏低,可以用to_dict('records')先把整个DataFrame转为每行的字典列表,再提取目标字段:

# 将DataFrame转为每行的字典列表
row_dicts = df.to_dict('records')

# 构造结果DataFrame
result = pd.DataFrame({
    'id': [d['id'] for d in row_dicts],
    'infos': [{k: d[k] for k in mapper['infos']} for d in row_dicts],
    'meta': [{k: d[k] for k in mapper['meta']} for d in row_dicts]
})

print(result)

这个方法避免了逐行遍历,性能更优。

原代码问题说明

你之前的代码没有指定axis=1,默认是按列(axis=0)处理,所以得到的是每列的全局字典(包含该列所有行的值),而非每行的局部字典。加上axis=1即可修正逻辑。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.15 15:23:09