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

使用Python pandas将IntegerArray转为列表时tolist报错如何解决

报错原因

你使用的pandas可空整数类型Int64底层用IntegerArray存储,它不属于numpy数组类型,本身没有实现tolist()方法,调用unique()返回的就是IntegerArray对象,所以直接调用方法会触发报错。

解决方法

这里提供三种常用的可行方案,你可以根据自己的场景选择:

  • 方案1:直接用内置list()函数转换,写法最简单
    res = list(df['col1'].unique())
    
  • 方案2:先转成numpy数组再调用tolist()
    res = df['col1'].unique().to_numpy().tolist()
    
  • 方案3:填充空值后直接转成普通numpy整数类型,后续操作完全兼容原生写法
    因为你已经调用fillna(0)把所有空值替换成了0,不存在缺失值,完全可以转成普通的int64类型,后面再调用任何numpy兼容的方法都不会有问题:
    # 转成普通int64类型
    df['col1'] = df['col1'].fillna(0).astype('int64')
    # 后续直接调用tolist不会报错
    res = df['col1'].unique().tolist()
    

内容的提问来源于stack exchange,提问作者The Great。

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.03 07:57:04