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

如何从DataFrame的字典列表列中提取Vendor类型的ID值

提取DataFrame中type为Vendor的字典ID值

示例数据构造

先构造符合需求的DataFrame:

import pandas as pd

data = {
    'ColumnName': [
        [],
        [{'ID': 'D6130732', 'type': 'Driver'}, {'ID': 'V169R454', 'type': 'Vendor'}],
        [{'ID': 'V1139I98', 'type': 'Vendor'}],
        [{'ID': 'D13090632', 'type': 'Driver'}],
        [{'ID': 'V682541632', 'type': 'Vendor'}, {'ID': 'D1852432', 'type': 'Driver'}],
        [],
        []
    ]
}
df = pd.DataFrame(data)

解决方案

用apply结合lambda表达式,直接提取每个列表中type为Vendor的字典对应的ID,无匹配项或空列表时返回None,最后过滤空值行:

# 提取Vendor的ID,无匹配则返回None
df['columnName'] = df['ColumnName'].apply(
    lambda x: next((d['ID'] for d in x if d.get('type') == 'Vendor'), None)
)
# 过滤空值并重置索引
df = df.dropna(subset=['columnName']).reset_index(drop=True)

最终结果

运行代码后得到的DataFrame:

columnName
0  V169R454
1  V1139I98
2  V682541632

补充说明

  • 若单个列表存在多个Vendor类型字典,上述代码返回第一个匹配的ID;需提取所有匹配项的话,可将next()改为列表推导式[d['ID'] for d in x if d.get('type') == 'Vendor'];
  • 用d.get('type')替代d['type'],能避免字典无type键时抛出异常,提升代码健壮性。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.09 13:35:18