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

如何在保留NaN值的前提下拆分Pandas中含字典的列为多列

解决方案

核心思路

先对Other_Name列的NaN值做兼容处理,再展开字典生成目标列,全程保留原NaN行不删除。

完整代码

import pandas as pd
import numpy as np

# 原始DataFrame
df = pd.DataFrame({
    'Name': ['AZ', 'AF'], 
    'Other_Name': [np.nan, [{'name': 'ARES ZAN', 'language': 'en', 'type': 'ALTERNATIVE'}]]
})

# 1. 预处理:NaN替换为含空字典的列表,取出列表内的字典元素
df['Other_Name'] = df['Other_Name'].apply(lambda x: [{}] if pd.isna(x) else x)
temp_col = df['Other_Name'].str[0]

# 2. 展开字典为多列,添加指定前缀
expanded_cols = temp_col.apply(pd.Series).add_prefix('Other_Name_')

# 3. 拼接回原表,删除原始列
df = pd.concat([df.drop('Other_Name', axis=1), expanded_cols], axis=1)

输出结果

处理后df的结构如下:

NameOther_Name_nameOther_Name_languageOther_Name_type
AZNaNNaNNaN
AFARES ZANenALTERNATIVE

兼容说明

如果你的Other_Name列中部分列表包含多个字典,可以先调用df = df.explode('Other_Name', ignore_index=True)展开列表,再执行后续处理即可。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.04 17:00:01