Pandas DataFrame rename() 方法
定义和用法
rename() 方法允许您更改行索引和列标签。
实例
重命名 DataFrame 的行索引:
import pandas as pd
data = {
"age": [50, 40, 30],
"qualified": [True, False, False]
}
idx = ["Sally", "Mary", "John"]
df = pd.DataFrame(data, index=idx)
newdf = df.rename({"Sally": "Pete", "Mary": "Patrick", "John": "Paula"})
print(newdf)
语法
dataframe.rename(mapper, index, columns, axis, copy, inplace, level, errors)
参数
index、columns、axis、copy、inplace、level、errors 参数是关键字参数。
| 参数 | 值 | 描述 |
|---|---|---|
| mapper | 可选。字典,其中旧索引/标签是键,新索引/标签是值。 | |
| index | 旧的索引和新的索引作为键值对 | 可选。字典,其中旧索引是键,新索引是值。 |
| columns | 旧的标签和新的标签作为键值对 | 可选。字典,其中旧标签是键,新标签是值。 |
| axis |
|
可选。执行重命名的轴(如果 mapper 参数存在且未指定 index 或 columns,则很重要)。 默认为 0。 |
| copy |
|
可选。是否也复制底层数据。 默认为 True。 |
| inplace |
|
可选。默认为 False。
|
| level |
|
可选。指定在使用 MultiIndex DataFrames 时要重命名的级别。 |
| errors |
|
可选。指定如果 DataFrame 中不存在此类索引/标签,是否返回错误。 默认为 'ignore'。 |
返回值
包含结果的 DataFrame,如果 inplace 参数设置为 True,则返回 None。
此函数不会更改原始 DataFrame 对象。