DataFrame.rename_axis(self, mapper=None, index=None, columns=None, axis=None, copy=True, inplace=False) [source]
设置索引或列的axis名称。
参数: | mapper : 设置axis名称属性的值。 index, columns : 类似 标量,类似于列表,类似于 以应用于该axis的值。 使用mapper和axis, 可以使用 指定要指定的轴。 在版本0.24.0中更改。 axis : {0 或 ‘index’, 1 或 ‘columns’}, 默认为 重命名的轴。 copy : 还要复制底层数据。 inplace : 直接修改对象, 而不是创建新的 |
返回值: | Series, DataFrame, 或 None 类型与调用者相同,如果 则为 |
Notes
DataFrame.rename_axis
支持两种调用约定
- (index=index_mapper, columns=columns_mapper, ...)
- (mapper, axis={'index', 'columns'}, ...)
第一个调用约定将仅修改索引的名称和/或作为列的Index
对象的名称。在这种情况下,该参数将copy
被忽略。
如果映射器是列表或标量,则第二个调用约定将修改相应索引的名称。但是,如果mapper
是dict
类或函数,它将使用不推荐的行为来修改轴标签。
强烈建议使用关键字参数来阐明意图。
例子
1)设置行索引名称
import pandas as pd df = pd.DataFrame([[1, 2], [3, 4]], columns=["A", "B"]) df2 = df.rename_axis("row_index") print(df2)
2)设置列索引名称
import pandas as pd df = pd.DataFrame([[1, 2], [3, 4]], columns=["A", "B"]) df3 = df.rename_axis("column_index", axis=1) print(df3)
3)同时设置行和列索引名称
import pandas as pd df = pd.DataFrame([[1, 2], [3, 4]], columns=["A", "B"]) df4 = df.rename_axis(index="row_index", columns="col_index") print(df4)
4)修改多级索引的名称
import pandas as pd df = pd.DataFrame({ "num_legs": [4, 4, 2], "num_arms": [0, 0, 2] }, index=["dog", "cat", "monkey"]) df.index = pd.MultiIndex.from_product( [['mammal'], ['dog', 'cat', 'monkey']], names=['type', 'name'] ) print(df) # 修改行索引名称 print(df.rename_axis(index={'type': 'class'})) df.columns.name = 'limbs' # 给列索引命名 # 将列索引名称转换为大写 print(df.rename_axis(columns=str.upper))