[英]Convert a dictionary of dictionaries to dataframe
我正在嘗試將字典字典轉換為 DataFrame,如下所示:
objs = {
'2022-05-12Delhivery Goa Warehouse': {'Blue Racks': 6, 'HPT': 6, 'Plastic Pallet': 40, 'Trolley': 48},
'2022-05-15Delhivery Goa Warehouse': {'Blue Racks': 6, 'HPT': 6, 'Plastic Pallet': 40, 'Trolley': 48},
'2022-05-18Delhivery Goa Warehouse': {'Blue Racks': 6, 'HPT': 6, 'Plastic Pallet': 40, 'Trolley': 48},
'2022-05-19Delhivery Goa Warehouse': {'Blue Racks': 6, 'HPT': 6, 'Plastic Pallet': 40, 'Trolley': 48},
'2022-05-19Delhivery Tauru Warehouse': {},
'2022-05-20Delhivery Goa Warehouse': {}
}
df_origcount = pd.DataFrame.from_dict(objs, orient='index')
df_origcount.reset_index(inplace=True)
from_dict
工作正常,直到遇到空字典。 它只是跳過該行並移動到下一行。 所以創建的數據框缺少最后兩個條目。
如何在字典為空的地方添加0
?
這樣數據框看起來像這樣:
index Blue Racks HPT Plastic Pallet Trolley
0 2022-05-12Delhivery Goa Warehouse 6 6 40 48
1 2022-05-15Delhivery Goa Warehouse 6 6 40 48
2 2022-05-18Delhivery Goa Warehouse 6 6 40 48
3 2022-05-19Delhivery Goa Warehouse 6 6 40 48
3 2022-05-19Delhivery Tauru Warehouse 0 0 0 0
3 2022-05-20Delhivery Goa Warehouse 0 0 0 0
在重置索引fill_value
reindex
索引:
df_origcount = (pd.DataFrame.from_dict(objs, orient='index')
.reindex(objs, fill_value=0)
.reset_index()
)
注意。 盡可能避免使用inplace=True
,這不能創建管道。
輸出:
index Blue Racks HPT Plastic Pallet Trolley
0 2022-05-12Delhivery Goa Warehouse 6 6 40 48
1 2022-05-15Delhivery Goa Warehouse 6 6 40 48
2 2022-05-18Delhivery Goa Warehouse 6 6 40 48
3 2022-05-19Delhivery Goa Warehouse 6 6 40 48
4 2022-05-19Delhivery Tauru Warehouse 0 0 0 0
5 2022-05-20Delhivery Goa Warehouse 0 0 0 0
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.