Python - 如何使用字典重新命名 Pandas DataFrame 中的多個列標題?
若要重新命名多個列標題,請使用 rename() 方法並在 **columns** 引數中設定字典。首先,讓我們建立一個 DataFrame −
dataFrame = pd.DataFrame({"Car": ['BMW', 'Mustang', 'Tesla', 'Mustang', 'Mercedes', 'Tesla', 'Audi'],"Cubic Capacity": [2000, 1800, 1500, 2500, 2200, 3000, 2000],"Reg Price": [7000, 1500, 5000, 8000, 9000, 6000, 1500],"Units Sold": [ 200, 120, 150, 120, 210, 250, 220]
})建立一個字典,用於重新命名列。鍵值對作為舊名稱和新名稱 −
dictionary = {'Car': 'Car Name','Cubic Capacity': 'CC','Reg Price': 'Registration Price','Units Sold': 'Units Purchased'
}使用 rename() 並將字典設定為 columns −
dataFrame.rename(columns=dictionary, inplace=True)
示例
以下是程式碼 −
import pandas as pd
# creating dataframe
dataFrame = pd.DataFrame({"Car": ['BMW', 'Mustang', 'Tesla', 'Mustang', 'Mercedes', 'Tesla', 'Audi'],"Cubic Capacity": [2000, 1800, 1500, 2500, 2200, 3000, 2000],"Reg Price": [7000, 1500, 5000, 8000, 9000, 6000, 1500],"Units Sold": [ 200, 120, 150, 120, 210, 250, 220]
})
print"DataFrame ...\n",dataFrame
# creating a dictionary to rename columns
# key and value pairs as old name and new name
dictionary = {'Car': 'Car Name','Cubic Capacity': 'CC','Reg Price': 'Registration Price','Units Sold': 'Units Purchased'
}
# using rename() and setting the dictionary as columns
dataFrame.rename(columns=dictionary, inplace=True)
print"\nUpdated DataFrame ...\n",dataFrame輸出
這將產生以下輸出 −
DataFrame ... Car Cubic Capacity Reg Price Units Sold 0 BMW 2000 7000 200 1 Mustang 1800 1500 120 2 Tesla 1500 5000 150 3 Mustang 2500 8000 120 4 Mercedes 2200 9000 210 5 Tesla 3000 6000 250 6 Audi 2000 1500 220 Updated DataFrame ... Car Name CC Registration Price Units Purchased 0 BMW 2000 7000 200 1 Mustang 1800 1500 120 2 Tesla 1500 5000 150 3 Mustang 2500 8000 120 4 Mercedes 2200 9000 210 5 Tesla 3000 6000 250 6 Audi 2000 1500 220
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP