pandas.Series.rename_axis#
- Series.rename_axis(mapper=None, index=None, columns=None, axis=None, copy=True, inplace=False)[源代码]#
设置索引或列的轴的名称。
- 参数
- mapper标量、列表式、可选
值以设置轴名称属性。
- 索引,列标量、列表、字典或函数,可选
要应用于该轴的值的标量、类似列表、类似字典或函数转换。请注意,
columns
如果对象是Series,则不允许使用参数。此参数仅适用于DataFrame类型的对象。使用以下任一选项
mapper
和axis
指定作为目标的轴的步骤mapper
,或index
和/或columns
。- axis{0或‘index’,1或‘Columns’},默认为0
要重命名的轴。
- copy布尔值,默认为True
还要复制底层数据。
- inplace布尔值,默认为False
直接修改对象,而不是创建新的Series或DataFrame。
- 退货
- 系列、DataFrame或无
与调用方相同的类型,如果
inplace=True
。
参见
Series.rename
更改系列索引标签或名称。
DataFrame.rename
更改DataFrame索引标签或名称。
Index.rename
在索引上设置新名称。
注意事项
DataFrame.rename_axis
支持两种调用约定(index=index_mapper, columns=columns_mapper, ...)
(mapper, axis={'index', 'columns'}, ...)
第一个调用约定将只修改索引的名称和/或作为列的Index对象的名称。在本例中,参数
copy
被忽略。如果映射器是列表或标量,则第二个调用约定将修改相应索引的名称。但是,如果映射器类似于DICT或函数,则它将使用修改轴的弃用行为 标签 。
我们 高度 建议使用关键字参数来阐明您的意图。
示例
Series
>>> s = pd.Series(["dog", "cat", "monkey"]) >>> s 0 dog 1 cat 2 monkey dtype: object >>> s.rename_axis("animal") animal 0 dog 1 cat 2 monkey dtype: object
DataFrame
>>> df = pd.DataFrame({"num_legs": [4, 4, 2], ... "num_arms": [0, 0, 2]}, ... ["dog", "cat", "monkey"]) >>> df num_legs num_arms dog 4 0 cat 4 0 monkey 2 2 >>> df = df.rename_axis("animal") >>> df num_legs num_arms animal dog 4 0 cat 4 0 monkey 2 2 >>> df = df.rename_axis("limbs", axis="columns") >>> df limbs num_legs num_arms animal dog 4 0 cat 4 0 monkey 2 2
MultiIndex
>>> df.index = pd.MultiIndex.from_product([['mammal'], ... ['dog', 'cat', 'monkey']], ... names=['type', 'name']) >>> df limbs num_legs num_arms type name mammal dog 4 0 cat 4 0 monkey 2 2
>>> df.rename_axis(index={'type': 'class'}) limbs num_legs num_arms class name mammal dog 4 0 cat 4 0 monkey 2 2
>>> df.rename_axis(columns=str.upper) LIMBS num_legs num_arms type name mammal dog 4 0 cat 4 0 monkey 2 2