Pandas DataFrame.rename 重命名行或列详解

键盘旁的猫
键盘旁的猫
发布时间:2026-10-13 | 3人浏览过
原创

本文介绍Pandas库中DataFrame.rename函数的使用方法,用于重命名数据框的行索引或列名。详细解析了mapper、index、columns、axis等关键参数,对比了两种调用约定,并通过代码示例演示了字典映射与函数转换的实际效果,帮助开发者高效进行数据预处理。

DataFrame.rename 函数概述

在Pandas库中,DataFrame.rename 是用于修改数据框轴标签的核心方法。

该函数的完整调用语法为:DataFrame.rename(mapper=None, index=None, columns=None, axis=None, copy=True, inplace=False, level=None)。

其主要功能是更改数据框的轴标签,即行索引或列名。

需要注意的是,传递给 mapper 的字典值必须保持唯一性(一对一映射)。对于未包含在字典或 Series 中的标签,系统将保留其原始名称;若字典中列出了数据框中不存在的额外标签,也不会引发错误。

参数:

mapper, index, columns : dict-like or function, optional

dict-like or functions transformations to apply to that axis' values. Use either mapperand axis to specify the axis to target with mapper, or index and columns.

dict-like 或函数转换以应用于该轴的值。二者必选其一mapper,并使用axis指定轴与目标mapper,或index和 columns。

主要用于指定需要修改的地方:index or columns

axis : int or str, optional

Axis to target with mapper. Can be either the axis name (‘index', ‘columns') or number (0, 1). The default is ‘index'.

轴与目标mapper。可以是轴名称('index','columns')或数字(0,1)。默认为'index'。

copy : boolean, default True

Also copy underlying data

还复制基础数据

inplace : boolean, default False

Whether to return a new DataFrame. If True then value of copy is ignored.

是否返回新的DataFrame。如果为True,则忽略复制值。

level : int or level name, default None

In case of a MultiIndex, only rename labels in the specified level.

如果是MultiIndex,只重命名指定级别的标签。

返回:

renamed : DataFrame

调用约定与参数详解

以下是具体的使用示例。

DataFrame.rename 方法支持两种不同的调用约定。

  • 第一种方式是通过关键字参数指定目标轴:(index=index_mapper, columns=columns_mapper, ...)。
  • 第二种方式是通过 mapper 配合 axis 参数指定目标:(mapper, axis={'index', 'columns'}, ...)。

为了代码的可读性和意图的清晰表达,强烈建议开发者使用关键字参数的方式来调用该函数。

代码示例演示


>>> df = pd.DataFrame({"A": [1, 2, 3], "B": [4, 5, 6]})
>>> df.rename(index=str, columns={"A": "a", "B": "c"})
  a c
0 1 4
1 2 5
2 3 6
>>> df.rename(index=str, columns={"A": "a", "C": "c"})
  a B
0 1 4
1 2 5
2 3 6
 
 
#使用轴样式参数
 
>>> df.rename(str.lower, axis='columns')
  a b
0 1 4
1 2 5
2 3 6
>>> df.rename({1: 2, 2: 4}, axis='index')
  A B
0 1 4
2 2 5
4 3 6

以上就是关于 Pandas 重命名功能的完整介绍,希望能为您的数据处理工作提供帮助,欢迎持续关注本站获取更多技术内容。

本站声明

本文内容仅供参考,不代表本站观点。转载或引用请注明出处。如发现内容问题,请通过联系我们页面反馈。

Python 相关产品和应用

全部下载

专题列表