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

DataFrame嵌套字典处理遇KeyError,求生成计数列解决方案

解决嵌套字典DataFrame的KeyError并提取通道计数

问题分析

你遇到的KeyError是因为部分行的spikes字典中不存在'20230516_1352_E_sorted'这个键,直接通过方括号取值会触发报错。我们需要用安全的取值方式避免这个问题,同时提取所有以chan1_开头的键对应的列表长度,生成新列。

解决方案

方法1:针对固定第一层键的场景

如果所有行的第一层键都是'20230516_1352_E_sorted',仅部分行可能缺失该键,用以下代码:

import pandas as pd

def get_chan_counts(spike_entry):
    # 安全获取内层字典,缺失时返回空字典
    inner_dict = spike_entry.get('20230516_1352_E_sorted', {})
    # 筛选chan1_开头的键,计算对应列表长度
    return {k: len(v) for k, v in inner_dict.items() if k.startswith('chan1_')}

# 应用函数提取计数,转为DataFrame
chan_count_df = df['spikes'].apply(get_chan_counts).apply(pd.Series)
# 合并到原DataFrame
df = pd.concat([df, chan_count_df], axis=1)

方法2:针对第一层键不固定的场景

如果不同行的第一层键可能不同(比如日期前缀变化),可以遍历所有第一层字典提取目标键:

import pandas as pd

def get_chan_counts(spike_entry):
    chan_counts = {}
    # 遍历所有内层字典
    for inner_dict in spike_entry.values():
        for k, v in inner_dict.items():
            if k.startswith('chan1_'):
                chan_counts[k] = len(v)
    return chan_counts

# 应用并合并
chan_count_df = df['spikes'].apply(get_chan_counts).apply(pd.Series)
df = pd.concat([df, chan_count_df], axis=1)

效果说明

  • 运行后,原DataFrame会新增所有以chan1_开头的列,列值为对应列表的元素数量。
  • 若某行没有对应通道的键,该列值会填充为NaN,可根据需求用fillna(0)转为0。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.20 15:53:16