You need to enable JavaScript to run this app. 将含列表元素的Pandas Series转为二维NumPy数组的优化方案
优惠活动
大模型
产品
解决方案
定价
更多

将含列表元素的Pandas Series转为二维NumPy数组的优化方案

将混合元素的Pandas Series转换为指定二维NumPy数组

输入与目标

输入的Pandas Series

import pandas as pd

s = pd.Series([1, 3, 2, [1, 3, 7, 8], [6, 6, 10, 4], 5])

目标二维NumPy数组

np.array([
    [ 1.,  1.,  1.,  1.],
    [ 3.,  3.,  3.,  3.],
    [ 2.,  2.,  2.,  2.],
    [ 1.,  3.,  7.,  8.],
    [ 6.,  6., 10.,  4.],
    [ 5.,  5.,  5.,  5.]
])

现有实现方案

当前方案需要将数组转为DataFrame再转回数组,存在不必要的结构转换开销:

import numpy as np
import pandas as pd
from itertools import zip_longest

# Convert series and each element in series into list
ls = list(map(lambda v: v if isinstance(v, list) else [v], s.to_list()))
# Cast list elements to 2d numpy array with longest list element as column number
a = np.array(list(zip_longest(*ls, fillvalue=np.nan))).T
# Convert to DataFrame, apply 'ffill' row-wise and re-convert to numpy array
a = pd.DataFrame(a).fillna(method="ffill", axis=1).values

更优替代方案(假设所有列表元素长度一致)

利用NumPy的full函数直接生成重复值数组,全程无需依赖DataFrame,步骤简洁高效:

import numpy as np
import pandas as pd

s = pd.Series([1, 3, 2, [1, 3, 7, 8], [6, 6, 10, 4], 5])

# 获取目标列数(从第一个列表元素提取,基于所有列表长度相同的假设)
col_count = next(len(item) for item in s if isinstance(item, list))

# 逐个处理Series元素:单个值重复col_count次,列表直接保留
result_array = np.array(
    [np.full(col_count, val, dtype=np.float64) if not isinstance(val, list) else val 
     for val in s],
    dtype=np.float64
)

print(result_array)

方案说明

  1. 遍历Series提取第一个列表元素的长度,确定目标数组的列数
  2. 用列表推导式处理每个元素:
    • 若为单个数值,用np.full生成对应长度的重复值数组
    • 若为列表,直接转为NumPy数组
  3. 将所有处理后的元素组合成二维NumPy数组,指定float64类型匹配目标格式

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.20 04:28:26