Python - 在不使用 rename() 的情况下按 Pandas DataFrame 中的索引重命名列名
我们可以轻松地按索引重命名列,即不使用rename().导入所需的库-
import pandas as pd
创建一个包含3列的DataFrame-
dataFrame = pd.DataFrame( { "Car": ['BMW', 'Lexus', 'Tesla', 'Mustang', 'Mercedes', 'Jaguar'],"Reg_Price": [7000, 1500, 5000, 8000, 9000, 6000],"Units": [90, 120, 100, 150, 200, 130] } )
现在让我们使用columns.values[0[通过在方括号中设置要更改的列的索引来重命名所有列-
dataFrame.columns.values[0] = "Car Names" dataFrame.columns.values[1] = "Registration Cost" dataFrame.columns.values[2] = "Units_Sold"
示例
以下是代码-
import pandas as pd #创建数据帧 dataFrame = pd.DataFrame( { "Car": ['BMW', 'Lexus', 'Tesla', 'Mustang', 'Mercedes', 'Jaguar'],"Reg_Price": [7000, 1500, 5000, 8000, 9000, 6000],"Units": [90, 120, 100, 150, 200, 130] } ) print"DataFrame ...\n",dataFrame #重命名列名称 dataFrame.columns.values[0] = "Car Names" dataFrame.columns.values[1] = "Registration Cost" dataFrame.columns.values[2] = "Units_Sold" print"\nUpdated DataFrame with new column names...\n",dataFrame输出结果
这将产生以下输出-
DataFrame ... Car Reg_Price Units 0 BMW 7000 90 1 Lexus 1500 120 2 Tesla 5000 100 3 Mustang 8000 150 4 Mercedes 9000 200 5 Jaguar 6000 130 Updated DataFrame with new column names... Car Names Registration Cost Units_Sold 0 BMW 7000 90 1 Lexus 1500 120 2 Tesla 5000 100 3 Mustang 8000 150 4 Mercedes 9000 200 5 Jaguar 6000 130