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

使用Pandas crosstab报错:unstack()参数数量不符

解决pd.crosstab报错:TypeError: unstack() takes from 2 to 3 positional arguments but 4 were given

尝试用以下代码创建交叉表:

import pandas as pd 
from seaborn import load_dataset

dfx = load_dataset("tips")

pd.crosstab(dfx['time'], dfx['day'])

运行后出现报错:

Traceback (most recent call last):

  Cell In[196], line 1
    pd.crosstab(dfx['time'], dfx['day'])

  File ~\anaconda3\Lib\site-packages\pandas\core\reshape\pivot.py:711 in crosstab

  File ~\anaconda3\Lib\site-packages\pandas\core\frame.py:9193 in pivot_table
    Difference with following row

  File ~\anaconda3\Lib\site-packages\pandas\core\reshape\pivot.py:99 in pivot_table
    values,

  File ~\anaconda3\Lib\site-packages\pandas\core\reshape\pivot.py:189 in __internal_pivot_table
    v in data

  File ~\anaconda3\Lib\site-packages\pandas\core\frame.py:9625 in unstack
    Note that a vectorized version of `func` often exists, which will

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

问题原因

这个报错属于pandas版本兼容性问题,旧版本的pandas在内部调用unstack()时存在参数传递错误,导致执行pd.crosstab时触发异常。

解决方案

  1. 升级pandas到稳定版本
    执行以下命令更新pandas:
pip install --upgrade pandas

升级后重新运行原代码即可正常生成交叉表。

  1. 替代实现方式
    如果暂时无法升级版本,可以用pd.pivot_table实现相同的交叉表功能:
import pandas as pd 
from seaborn import load_dataset

dfx = load_dataset("tips")
# 用pivot_table生成交叉表,aggfunc='size'统计数量,fill_value=0填充空值
pd.pivot_table(dfx, index='time', columns='day', aggfunc='size', fill_value=0)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.05 23:33:21