繁体   English   中英

将字典字典转换为数据框

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM