pandas.DataFrame.rename#
- DataFrame.rename(mapper=None, *, index=None, columns=None, axis=None, copy=True, inplace=False, level=None, errors='ignore')[源代码]#
更改轴标签。
函数/DICT值必须唯一(1对1)。词典/系列中未包含的标签将保留原样。列出的额外标签不会引发错误。
请参阅 user guide 想要更多。
- 参数
- mapper类词典或函数
要应用于该轴的值的类字典或函数转换。使用以下任一选项
mapper
和axis
指定作为目标的轴的步骤mapper
,或index
和columns
。- index类词典或函数
指定轴的替代方法 (
mapper, axis=0
相当于index=mapper
)。- columns类词典或函数
指定轴的替代方法 (
mapper, axis=1
相当于columns=mapper
)。- axis{0或‘index’,1或‘Columns’},默认为0
作为目标的轴
mapper
。可以是轴名称(‘index’,‘Columns’)或编号(0,1)。缺省值为‘index’。- copy布尔值,默认为True
还要复制底层数据。
- inplace布尔值,默认为False
是否返回新的DataFrame。如果为True,则忽略Copy的值。
- levelInt或Level名称,默认为无
如果是多重索引,则仅重命名指定级别的标签。
- errors{‘Ignore’,‘RAISE’},默认‘Ignore’
如果为“Raise”,则引发一个 KeyError 当一个像字典一样的东西 mapper , index ,或 columns 包含正在转换的索引中不存在的标签。如果为‘Ignore’,现有密钥将被重命名,多余的密钥将被忽略。
- 退货
- DataFrame或无
具有重命名的轴标签的DataFrame,如果
inplace=True
。
- 加薪
- 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='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