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

如何用链式调用方式将Pandas DataFrame的列表列拆分为多列?

Pandas链式调用拆分列表列的优化方案

问题描述

我有一个包含列表类型列的Pandas DataFrame,示例如下:

>>> import pandas as pd
>>> d = {'A': [1, 2, 3], 'B': [[0.1, 0.2, 0.3], [0.4, 0.5, 0.6], [0.7, 0.8, 0.9]]}
>>> df = pd.DataFrame(data=d)
>>> df
   A                B
0  1  [0.1, 0.2, 0.3]
1  2  [0.4, 0.5, 0.6]
2  3  [0.7, 0.8, 0.9]

我可以通过以下方式将这些列表拆分为单独的列:

>>> df[['x','y','z']] = df.B.tolist()
>>> df
   A                B    x    y    z
0  1  [0.1, 0.2, 0.3]  0.1  0.2  0.3
1  2  [0.4, 0.5, 0.6]  0.4  0.5  0.6
2  3  [0.7, 0.8, 0.9]  0.7  0.8  0.9

但我希望使用支持链式调用的命令来完成此操作。我考虑过使用.assign方法,但需要显式定义每个变量,通过lambda进行拆分的过程较为繁琐:

>>> (df.assign(q=lambda df_: df_.B.apply(lambda x: x[0]),
...            w=lambda df_: df_.B.apply(lambda x: x[1]),
...            u=lambda df_: df_.B.apply(lambda x: x[2])))
   A                B    q    w    u
0  1  [0.1, 0.2, 0.3]  0.1  0.2  0.3
1  2  [0.4, 0.5, 0.6]  0.4  0.5  0.6
2  3  [0.7, 0.8, 0.9]  0.7  0.8  0.9

请问有没有更优的实现方式?

解决方案

方法1:解包DataFrame结合.assign

直接将列表列转换为DataFrame,通过字典解包传入.assign,无需逐个定义列:

result = (
    df.assign(**pd.DataFrame(df.B.tolist(), index=df.index, columns=['x', 'y', 'z']))
)
print(result)

输出:

A                B    x    y    z
0  1  [0.1, 0.2, 0.3]  0.1  0.2  0.3
1  2  [0.4, 0.5, 0.6]  0.4  0.5  0.6
2  3  [0.7, 0.8, 0.9]  0.7  0.8  0.9

若不需要自定义列名,可省略columns参数,使用默认数字列名:

result = df.assign(**pd.DataFrame(df.B.tolist(), index=df.index))

方法2:.join链式拼接

将列表列转为独立DataFrame后,直接与原DataFrame链式拼接,代码更直观:

result = (
    df.join(pd.DataFrame(df.B.tolist(), index=df.index, columns=['x', 'y', 'z']))
)
print(result)

此方法不修改原DataFrame,完全符合链式调用的需求。

方法3:动态长度列表处理(explode+pivot)

如果列表列长度不固定,可先用explode展开列表,再通过pivot重构列:

result = (
    df.assign(idx=df.groupby(level=0).cumcount())
      .explode('B')
      .pivot(index=df.index, columns='idx', values='B')
      .rename(columns=lambda x: f'col{x}')
      .join(df)
)
print(result)

这种方式适合列表长度不一致的场景,固定长度列表优先选择前两种方法,效率更高。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.30 03:45:35