将字典列表附加到 Python 中的现有 Pandas DataFrame
使用 append() 方法,将字典列表附加到现有的 Pandas DataFrame。首先,创建一个 DataFrame −
dataFrame = pd.DataFrame( { "Car": ['BMW', 'Audi', 'XUV', 'Lexus', 'Volkswagen'],"Place": ['Delhi','Bangalore','Pune','Chandigarh','Mumbai'],"Units": [100, 150, 50, 110, 90] } )
创建字典列表 −
d = [{'Car': 'Mustang', 'Place': 'Hyderabad', 'Units': 60},{'Car': 'Tesla', 'Place': 'Kerala', 'Units': 30},{'Car': 'RollsRoyce', 'Place': 'Punjab', 'Units': 70},{'Car': 'Bentley', 'Place': 'Gujarat', 'Units': 80} ]
现在,将字典列表附加到已经创建的 DataFrame −
dataFrame = dataFrame.append(d, ignore_index=True, sort=False)
示例
以下为代码 −
import pandas as pd; dataFrame = pd.DataFrame( { "Car": ['BMW', 'Audi', 'XUV', 'Lexus', 'Volkswagen'],"Place": ['Delhi','Bangalore','Pune','Chandigarh','Mumbai'],"Units": [100, 150, 50, 110, 90] } ) print("DataFrame ...\n",dataFrame) # creating dictionaries d = [{'Car': 'Mustang', 'Place': 'Hyderabad', 'Units': 60},{'Car': 'Tesla', 'Place': 'Kerala', 'Units': 30},{'Car': 'RollsRoyce', 'Place': 'Punjab', 'Units': 70},{'Car': 'Bentley', 'Place': 'Gujarat', 'Units': 80} ] print("\n Dictionary....\n", d) # appending list of dictionaries to already created DataFrame dataFrame = dataFrame.append(d, ignore_index=True, sort=False) # Display the appended result print("\nResult of append...\n",dataFrame)
输出
该程序将产生以下输出 −
DataFrame ... Car Place Units 0 BMW Delhi 100 1 Audi Bangalore 150 2 XUV Pune 50 3 Lexus Chandigarh 110 4 Volkswagen Mumbai 90 Dictionary.... [{'Units': 60, 'Car': 'Mustang', 'Place': 'Hyderabad'}, {'Units': 30, 'Car': 'Tesla', 'Place': 'Kerala'}, {'Units': 70, 'Car': 'RollsRoyce', 'Place': 'Punjab'}, {'Units': 80, 'Car': 'Bentley', 'Place': 'Gujarat'}]) Result of append... Car Place Units 0 BMW Delhi 100 1 Audi Bangalore 150 2 XUV Pune 50 3 Lexus Chandigarh 110 4 Volkswagen Mumbai 90 5 Mustang Hyderabad 60 6 Tesla Kerala 30 7 RollsRoyce Punjab 70 8 Bentley Gujarat 80
广告