Pandas DataFrame ref_df_set_axis() 方法

定义和用法

set_axis() 方法允许您设置指定轴的索引。

使用 axis='columns' 参数可设置列的标签。

实例

命名 DataFrame 的行索引:

import pandas as pd

data = {
  "age": [50, 40, 30],
  "qualified": [True, False, False]
}
df = pd.DataFrame(data)

newdf = df.set_axis(["John", "Peter", "Alex"])

print(newdf)

亲自试一试

语法

dataframe.set_axis(labels, axis, inplace)

参数

indexcolumnsaxiscopyinplace 参数是关键字参数

参数 描述
labels 可选。包含索引的列表。
axis
  • 0
  • 1
  • 'index'
  • 'columns'

可选。要在其上设置索引的轴。

默认为 0。

inplace
  • True
  • False

可选。默认为 False。

  • 如果为 True:在当前 DataFrame 上完成索引。
  • 如果为 False:返回已完成索引的副本。

返回值

包含结果的 DataFrame,或者如果 inplace 参数设置为 True,则返回 None。