pandas.DataFrame.rename#
- DataFrame.rename(mapper=None, *, index=None, columns=None, axis=None, copy=None, inplace=False, level=None, errors='ignore')[源代码]#
重命名列或索引标签。
函数/字典值必须是唯一的(1 对 1)。不在字典/Series 中的标签将保持不变。列出的额外标签不会引发错误。
更多信息,请参阅 user guide 。
- Parameters:
- mapper类字典或函数
应用于该轴值的类字典或函数变换。使用
mapper和axis来指定mapper要指向的轴,或者使用index和columns。- index类字典或函数
指定轴的替代方法(
mapper, axis=0等同于index=mapper)。- columns类字典或函数
指定轴的替代方法(
mapper, axis=1等同于columns=mapper)。- axis{0 或 ‘index’, 1 或 ‘columns’}, default 0
要用
mapper指向的轴。可以是轴名(’index’, ‘columns’)或数字(0, 1)。默认为 ‘index’。- copybool, default True
同时复制底层数据。
备注
copy 关键字在 pandas 3.0 中将更改行为。Copy-on-Write 将默认启用,这意味着所有带有 copy 关键字的方法都将使用惰性复制机制来延迟复制并忽略 copy 关键字。copy 关键字将在 pandas 的未来版本中移除。
通过启用 copy on write
pd.options.mode.copy_on_write = True,您可以获得未来的行为和改进。- inplacebool,默认 False
是修改 DataFrame 还是创建新的 DataFrame。如果为 True,则忽略 copy 的值。
- levelint 或级别名称,默认为 None
对于 MultiIndex,仅重命名指定级别的标签。
- errors{‘ignore’, ‘raise’},默认为 ‘ignore’
如果为 ‘raise’,当类字典的
mapper、index或columns包含在要变换的 Index 中不存在的标签时,将引发 KeyError。如果为 ‘ignore’,将重命名存在的键,并忽略多余的键。
- Returns:
- DataFrame 或 None
已重命名轴标签的山<0xE5><0x87><0xBA>或在
inplace=True时为 None。
- Raises:
- KeyError
如果未在选定轴中找到任何标签且 “errors=’raise’”。
参见
DataFrame.rename_axis设置轴的名称。
Examples
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='object')
>>> df.rename(columns={"A": "a", "B": "b", "C": "c"}, errors="raise") Traceback (most recent call last): KeyError: ['C'] not found in 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