Python – Pandas Dataframe.rename()
在Pandas中重命名DataFrame列名非常简单。您需要做的就是使用该rename()方法并传递要更改的列名和新列名。让我们举一个例子,看看它是如何完成的。
步骤
创建二维、大小可变、潜在异构的表格数据df。
打印输入数据帧df。
使用rename()方法重命名列名。在这里,我们将使用新名称“new_x”重命名列“x”。
使用重命名的列打印DataFrame。
示例
import pandas as pd df = pd.DataFrame( { "x": [5, 2, 7, 0], "y": [4, 7, 5, 1], "z": [9, 3, 5, 1] } ) print "Input DataFrame is:\n", df df = df.rename(columns={"x": "new_x"}) print "After renaming, the DataFrame is:\n", df输出结果
Input DataFrame is: x y z 0 5 4 9 1 2 7 3 2 7 5 5 3 0 1 1 After renaming, the DataFrame is: new_x y z 0 5 4 9 1 2 7 3 2 7 5 5 3 0 1 1