Python - 重命名 Pandas DataFrame 的列
要重命名DataFrame的列,请使用rename()方法。在rename()方法的“columns”参数下设置要重命名的列名称。例如,将“Car”列更改为“CarName”-
dataFrame.rename(columns={'Car': 'Car Name'}, inplace=False)
首先,读取CSV并创建一个DataFrame-
dataFrame = pd.read_csv("C:\\Users\\amit_\\Desktop\\SalesRecords.csv")
现在,重命名列名。在这里,我们将重命名列“Car”、“Date_of_Purchase”和“Reg_Price”-
dataFrame = dataFrame.rename(columns={'Car': 'Car Name', 'Date_of_Purchase': 'Sold On', 'Reg_Price' : 'Booking Price'}, inplace=False)
示例
以下是代码
import pandas as pd #readingcsvfile dataFrame = pd.read_csv("C:\\Users\\amit_\\Desktop\\SalesRecords.csv") print("DataFrame...\n",dataFrame) #counttherowsandcolumnsinaDataFrame print("\nNumber of rows and column in our DataFrame = ",dataFrame.shape) dataFrame = dataFrame.rename(columns={'Car': 'Car Name', 'Date_of_Purchase': 'Sold On', 'Reg_Price' : 'Booking Price'}, inplace=False) print("\nDataFrame with updated Column Name ...\n",dataFrame)输出结果
这将产生以下输出-
DataFrame... Car Date_of_Purchase Reg_Price 0 BMW 10/10/2020 1000 1 Lexus 10/12/2020 750 2 Audi 10/17/2020 750 3 Jaguar 10/16/2020 1500 4 Mustang 10/19/2020 1100 5 Lamborghini 10/22/2020 1000 Number of rows and column in our DataFrame = (6, 3) DataFrame with updated Column Name ... Car Name Sold On Booking Price 0 BMW 10/10/2020 1000 1 Lexus 10/12/2020 750 2 Audi 10/17/2020 750 3 Jaguar 10/16/2020 1500 4 Mustang 10/19/2020 1100 5 Lamborghini 10/22/2020 1000