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

创建含列表列的Pandas DataFrame触发ValueError的问题排查

问题根源与解决方案

你遇到的ValueError是因为numpy无法创建形状不均一的数组——你给pets列传的是长度不一致的子列表(有的含2个元素,有的1个,有的3个),用np.array()包裹时,numpy默认会尝试生成规则的多维数组,但这些子列表长度不统一,导致创建失败。

方法1:直接使用Python原生列表(推荐)

Pandas本身支持将列表作为DataFrame的元素,无需用np.array()包裹pets的内容,直接传入原生列表即可:

import pandas as pd
import numpy as np

pets = pd.DataFrame({
    'sex': np.array(['M', 'M', 'F', 'M', 'F', 'F', 'F', 'M', 'F', 'M']),
    'age': np.array([21, 45, 23, 56, 47, 70, 34, 30, 19, 62]),
    'pets': [['cat', 'dog'],
             ['hamster'],
             ['cat', 'gerbil'],
             ['fish', 'hamster', 'gerbil'],
             ['cat'],
             ['dog'],
             ['dog'],
             ['cat'],
             ['rabbit', 'cat'],
             ['dog']]
})

方法2:指定numpy数组的dtype为object

如果一定要用numpy数组存储pets列,需要显式指定dtype=object,让numpy允许存储长度不一的序列:

import pandas as pd
import numpy as np

pets = pd.DataFrame({
    'sex': np.array(['M', 'M', 'F', 'M', 'F', 'F', 'F', 'M', 'F', 'M']),
    'age': np.array([21, 45, 23, 56, 47, 70, 34, 30, 19, 62]),
    'pets': np.array([['cat', 'dog'],
                      ['hamster'],
                      ['cat', 'gerbil'],
                      ['fish', 'hamster', 'gerbil'],
                      ['cat'],
                      ['dog'],
                      ['dog'],
                      ['cat'],
                      ['rabbit', 'cat'],
                      ['dog']], dtype=object)
})

运行任意一种代码,都能得到你预期的DataFrame样式,每一行的pets列都是对应的列表元素。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.27 02:20:19