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

pandas拆分全表列表格式列并提取每个列表首个元素的方法

正确解法

你之前的写法报错核心原因是apply默认按列遍历,传入函数的参数是整列的Series对象而非单个单元格的值,要对全表每个单元格做处理应该使用applymap方法,同时需要在处理函数中兼容三种不同的单元格类型:空值NaN、字符串格式的列表、真实列表结构。

完整实现代码

import pandas as pd
import numpy as np

# 单单元格处理函数
def extract_first(x):
    # 空值直接返回
    if pd.isna(x):
        return np.nan
    # 真实列表类型直接取第一个元素
    if isinstance(x, list):
        return x[0]
    # 字符串格式的列表先处理符号再拆分
    if isinstance(x, str):
        return x.strip('[]').split(',')[0]

# 测试数据构造
t = pd.DataFrame(data={'col1': ['[blah,blah]','[test,bing]',np.NaN], 'col2': ['[math,sci]',np.NaN,['number','4']]})

# 对全表每个单元格应用处理函数
res = t.applymap(extract_first)
print(res)

输出结果

col1   col2
0  blah   math
1  test    NaN
2   NaN  number

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.04 13:54:01