编写 Python 代码以重命名数据框中的给定轴
pythonpandasserver side programmingprogramming
假设您有一个数据框,重命名轴的结果是,
重命名索引: index Id Age Mark 0 1.0 12.0 80.0 1 2.0 12.0 90.0 2 3.0 14.0 NaN 3 NaN 13.0 95.0 4 5.0 NaN 85.0
解决方案
为了解决这个问题,我们将遵循下面给出的步骤 −
定义一个数据框
在轴名称中将 df.rename_axis() 函数应用为 ‘index’ 并设置 axis=1
df.rename_axis('index',axis=1)
示例
import pandas as pd df = pd.DataFrame({"Id":[1, 2, 3, None, 5], "Age":[12, 12, 14, 13, None], "Mark":[80, 90, None, 95, 85], }) print("Dataframe is:\n",df) print("Rename index:") df = df.rename_axis('index',axis=1) print(df)
输出
Dataframe is: Id Age Mark 0 1.0 12.0 80.0 1 2.0 12.0 90.0 2 3.0 14.0 NaN 3 NaN 13.0 95.0 4 5.0 NaN 85.0 Rename index: index Id Age Mark 0 1.0 12.0 80.0 1 2.0 12.0 90.0 2 3.0 14.0 NaN 3 NaN 13.0 95.0 4 5.0 NaN 85.0