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

如何将多键字典值映射回DataFrame列?

解决方案:在DataFrame副本中添加数组长度列

你完全不需要修改原DataFrame,只需要创建它的副本,再通过映射字典中的键来获取对应数组的长度,添加为新列即可。以下是具体步骤和代码:

步骤1:创建原DataFrame的副本

先复制原始数据,确保所有操作都不会影响原数据:

df_copy = df_perm.copy()

步骤2:构造与字典匹配的键对

你的字典键是由字符串类型的资产ID和字符串类型的日期组成的元组,所以需要在副本中生成格式完全一致的键:

# 替换成你DataFrame中实际的资产ID列名和日期列名
# 比如假设资产ID列是'asset_id',日期列是'asset_date'
df_copy['temp_key'] = list(zip(
    df_copy['asset_id'].astype(str),
    df_copy['asset_date'].astype(str)
))

步骤3:映射字典获取数组长度

使用apply从字典中提取对应数组的长度,用get方法避免键不存在时抛出KeyError(默认返回空数组的长度0):

df_copy['array_length'] = df_copy['temp_key'].apply(lambda k: len(perm_dict.get(k, [])))

步骤4(可选):清理临时列

如果不需要临时的temp_key列,可以删除它:

df_copy = df_copy.drop(columns=['temp_key'])

额外优化:简化字典的构建过程

你原来两次遍历DataFrame构建字典的方式可以优化成一次遍历,用collections.defaultdict自动初始化空列表,减少代码冗余:

from collections import defaultdict

perm_dict = defaultdict(list)
# 第一次遍历填充符合条件的数据
for row in df_perm.itertuples():
    key = (str(row[1]), str(row[3]))
    # 你的条件判断
    if row[6].to_datetime().date() < row[9].to_datetime().date() < row[5].to_datetime().date():
        perm_dict[key].append(row[10])
# 确保所有唯一键都存在(即使没有符合条件的数据)
for row in df_perm.itertuples():
    key = (str(row[1]), str(row[3]))
    if key not in perm_dict:
        perm_dict[key] = []

这样处理后,df_copy就是带有新列的DataFrame副本,原df_perm完全不受影响。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 04:15:27