pandas.DataFrame.rename#

DataFrame.rename(mapper=None, *, index=None, columns=None, axis=None, copy=<no_default>, inplace=False, level=None, errors='ignore')[源代码]#

重命名列或索引标签。

函数 / 字典的值必须是唯一的(一对一)。未包含在字典/Series 中的标签将保持不变。列出的额外标签不会引发错误。

更多信息请参见 用户指南

参数:
mapper类字典或函数

应用于该轴值的类字典或函数转换。使用 mapperaxis 来指定 mapper 要针对的轴,或者使用 indexcolumns

index类字典或函数

指定轴的替代方法(mapper, axis=0 等同于 index=mapper)。

columns类字典或函数

指定轴的替代方法(mapper, axis=1 等同于 columns=mapper)。

axis{0 或 ‘index’, 1 或 ‘columns’}, 默认为 0

mapper 要针对的轴。可以是轴名称(‘index’、‘columns’)或数字(0、1)。默认为‘index’。

copybool,默认值 False

此关键字已被忽略;更改其值将不会影响方法。

已弃用,版本 3.0.0: 此关键字已被忽略,并将在 pandas 4.0 中删除。自 pandas 3.0 起,此方法始终返回一个新对象,并使用延迟复制机制,该机制会推迟复制直到必要时(写时复制)。有关更多详细信息,请参阅关于写时复制的用户指南

inplacebool, default False

是否修改 DataFrame 而不是创建新的 DataFrame。如果为 True,则忽略 copy 的值。

levelint 或级别名称,默认为 None

对于 MultiIndex,仅重命名指定级别的标签。

errors{‘ignore’, ‘raise’}, default ‘ignore’

如果为 ‘raise’,则当类字典的 mapperindexcolumns 包含在要转换的 Index 中不存在的标签时,将引发 KeyError。如果为 ‘ignore’,则将重命名现有键,忽略额外键。

返回:
DataFrame 或 None

带有已重命名轴标签的 DataFrame,如果 inplace=True 则为 None。

引发:
KeyError

如果选定的轴中找不到任何标签且“errors=’raise’”.

另请参阅

DataFrame.rename_axis

设置轴的名称。

示例

DataFrame.rename 支持两种调用约定

  • (index=index_mapper, columns=columns_mapper, ...)

  • (mapper, axis={'index', 'columns'}, ...)

我们*强烈*建议使用关键字参数来阐明您的意图。

使用映射重命名列

>>> df = pd.DataFrame({"A": [1, 2, 3], "B": [4, 5, 6]})
>>> df.rename(columns={"A": "a", "B": "c"})
   a  c
0  1  4
1  2  5
2  3  6

使用映射重命名索引

>>> df.rename(index={0: "x", 1: "y", 2: "z"})
   A  B
x  1  4
y  2  5
z  3  6

将索引标签转换为不同的类型

>>> df.index
RangeIndex(start=0, stop=3, step=1)
>>> df.rename(index=str).index
Index(['0', '1', '2'], dtype='str')
>>> df.rename(columns={"A": "a", "B": "b", "C": "c"}, errors="raise")
Traceback (most recent call last):
KeyError: ['C'] not found in axis

使用 axis 样式的参数

>>> 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