重命名列名 – Python Pandas
我们可以使用 `rename()` 方法重命名列名。假设以下 Pandas DataFrame 由 3 列组成 -
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] } )
我们将重命名两列,即 “Car” 改为 “Car Names”,“Reg_Price” 改为 “Registration Cost”
dataFrame.rename(columns={dataFrame.columns[0]: 'Car Names', dataFrame.columns[1]: 'Registration Cost'})
示例
以下为代码 -
import pandas as pd # Create 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] } ) print"DataFrame ...\n",dataFrame # Renaming columns res = dataFrame.rename(columns={dataFrame.columns[0]: 'Car Names', dataFrame.columns[1]: 'Registration Cost'}) print"\nUpdated DataFrame with renamed column names...\n",res
输出
这将产生以下输出 -
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 renamed column names... Car Names Registration Cost 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
广告