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

如何将元素为列表的pd.Series转换为多列DataFrame

如何将元素为等长列表的Pandas Series重塑为保留原索引的DataFrame

问题场景

现有一个Pandas Series,每个元素都是长度相同的列表,需要将其转换为对应列数的DataFrame,同时保留原Series的索引。示例如下:

原Series:

import pandas as pd

s = pd.Series([[1, 10, 0.1], [2, 20, 0.2], [3, 30, 0.3]], index=['a', 'b', 'c'])
print(s)
# 输出:
# a    [1, 10, 0.1]
# b    [2, 20, 0.2]
# c    [3, 30, 0.3]
# dtype: object

期望得到的DataFrame:

df = pd.DataFrame([[1, 10, 0.1], [2, 20, 0.2], [3, 30, 0.3]],
                  index=['a', 'b', 'c'], columns=['X', 'Y', 'Z'])
print(df)
# 输出:
#    X   Y    Z
# a  1  10  0.1
# b  2  20  0.2
# c  3  30  0.3

解决方案

以下是几种常用的实现方式:

  • 方法一:利用tolist()转换为二维列表后构造DataFrame
    直接将Series的元素转换为二维列表,传入DataFrame构造器时指定原索引和自定义列名,这种方式效率较高,适合处理大数据量。

    df = pd.DataFrame(s.tolist(), index=s.index, columns=['X', 'Y', 'Z'])
    
  • 方法二:使用apply(pd.Series)拆分列表
    对Series的每个列表元素应用pd.Series,自动将列表拆分为多列,之后再重命名列名即可,代码简洁直观。

    df = s.apply(pd.Series)
    df.columns = ['X', 'Y', 'Z']
    
  • 方法三:通过from_records构造DataFrame
    from_records方法可直接处理二维数组/列表,同样支持指定索引和列名,也是高效的实现方式。

    df = pd.DataFrame.from_records(s.values, index=s.index, columns=['X', 'Y', 'Z'])
    

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

相关产品推荐
方舟 Agent Plan

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

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