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

使用pandas pivot_table遇TypeError:unstack()参数数量错误

使用pandas pivot_table时遭遇TypeError错误的解决办法

问题重现

调用pandas.pivot_table()时触发TypeError,错误提示:

TypeError: unstack() takes from 2 to 3 positional arguments but 4 were given

即使复制官方示例代码运行,仍出现相同错误。示例代码如下:

import pandas as pd

df = pd.DataFrame({"A": ["foo", "foo", "foo", "foo", "foo",
                         "bar", "bar", "bar", "bar"],
                   "B": ["one", "one", "one", "two", "two",
                         "one", "one", "two", "two"],
                   "C": ["small", "large", "large", "small",
                         "small", "large", "small", "small",
                         "large"],
                   "D": [1, 2, 2, 3, 3, 4, 5, 6, 7],
                   "E": [2, 4, 5, 5, 6, 6, 8, 9, 9]})
table = pd.pivot_table(df, values='D', index=['A', 'B'], columns=['C'], aggfunc="sum")

完整报错栈:

TypeError                                 Traceback (most recent call last)
<ipython-input-67-e8dff429bcc3> in <cell line: 10>()
      8                    "D": [1, 2, 2, 3, 3, 4, 5, 6, 7],
      9                    "E": [2, 4, 5, 5, 6, 6, 8, 9, 9]})
---&gt; 10 table = pd.pivot_table(df, values='D', index=['A', 'B'], columns=['C'], aggfunc="sum")

2 frames
/usr/local/lib/python3.10/dist-packages/pandas/core/frame.py in unstack(self, level, fill_value, sort)
   9620         return correl
   9621 
-&gt; 9622     # ----------------------------------------------------------------------
   9623     # ndarray-like stats methods
   9624 

TypeError: unstack() takes from 2 to 3 positional arguments but 4 were given

运行环境:Pandas 2.1.4、Python 3.10.12,Google Colab

解决方案

1. 检查unstack方法是否被篡改

在代码开头执行以下命令,确认DataFrame.unstack是否为pandas原生方法:

print(pd.DataFrame.unstack)

如果输出不是类似<function DataFrame.unstack at 0x...>的原生函数信息,说明该方法被其他代码覆盖,需要重启Colab运行时,并排查是否有自定义代码或第三方库修改了pandas的内置方法。

2. 重新安装指定版本的pandas

在Colab中执行以下命令,强制重新安装Pandas 2.1.4,修复可能的文件损坏:

!pip install --force-reinstall pandas==2.1.4

若仍无效,可尝试升级到最新稳定版:

!pip install --upgrade pandas

3. 排查第三方库冲突

检查是否导入了可能修改pandas行为的第三方库(如某些自定义扩展、过时的数据分析库),尝试暂时注释相关导入语句,重新运行代码验证是否解决问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.04 06:10:59