pd.MultiIndex() TypeError: __new__() got an unexpected keyword argument 'labels

2021-02-18 10:42:37 浏览数 (1)

问题:

代码语言:python代码运行次数:0复制
pd.MultiIndex(levels=[["a", "b"], [1, 2]],
              labels=[[0, 0, 1, 1], [0, 1, 0, 1]])

报错

代码语言:javascript复制
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-85-8f70470c90b8> in <module>
      1 pd.MultiIndex(levels=[["a", "b"], [1, 2]],
----> 2               labels=[[0, 0, 1, 1], [0, 1, 0, 1]])

TypeError: __new__() got an unexpected keyword argument 'labels'

原因:

查看帮助文档

代码语言:python代码运行次数:0复制
pd.MultiIndex?

以下是部分内容:

代码语言:python代码运行次数:0复制
Init signature:
pd.MultiIndex(
    levels=None,
    codes=None,
    sortorder=None,
    names=None,
    dtype=None,
    copy=False,
    name=None,
    verify_integrity: bool = True,
)
Docstring:     
A multi-level, or hierarchical, index object for pandas objects.

Parameters
----------
levels : sequence of arrays
    The unique labels for each level.
codes : sequence of arrays
    Integers for each level designating which label at each location.

    .. versionadded:: 0.24.0
sortorder : optional int
    Level of sortedness (must be lexicographically sorted by that
    level).
names : optional sequence of objects
    Names for each of the index levels. (name is accepted for compat).
copy : bool, default False
    Copy the meta-data.
verify_integrity : bool, default True
    Check that the levels/codes are consistent and valid.

Attributes
----------
names
levels
codes
nlevels
levshape

Methods
-------
from_arrays
from_tuples
from_product
from_frame
set_levels
set_codes
to_frame
to_flat_index
is_lexsorted
sortlevel
droplevel
swaplevel
reorder_levels
remove_unused_levels
get_locs

See Also
--------
MultiIndex.from_arrays  : Convert list of arrays to MultiIndex.
MultiIndex.from_product : Create a MultiIndex from the cartesian product
                          of iterables.
MultiIndex.from_tuples  : Convert list of tuples to a MultiIndex.
MultiIndex.from_frame   : Make a MultiIndex from a DataFrame.
Index : The base pandas Index type.

Notes
-----
See the `user guide
<https://pandas.pydata.org/pandas-docs/stable/user_guide/advanced.html>`_
for more.

可以看到pd.MultiIndex()并没有labels参数,与labels功能相同的是codes参数,查看https://pandas.pydata.org/pandas-docs/stable/user_guide/advanced.html可以看到:

Changed in version 0.24.0: MultiIndex.labels has been renamed to MultiIndex.codes and MultiIndex.set_labels to MultiIndex.set_codes.

也就是说从0.24.0版本开始,MultiIndex.labels已经改名为MultiIndex.codes.

解决:

将参数名labels改为codes即可

代码语言:python代码运行次数:0复制
pd.MultiIndex(levels=[["a", "b"], [1, 2]],
                    codes=[[0, 0, 1, 1], [0, 1, 0, 1]])

输出结果:

代码语言:javascript复制
MultiIndex([('a', 1),
            ('a', 2),
            ('b', 1),
            ('b', 2)],
           )

总结:

出现unexpected keyword argument时,一般是参数名打错了或者版本变更导致参数名改变(更名、弃用等),查看一下帮助文档,对照参数列表检查即可看出问题在哪。

0 人点赞