简体   繁体   English

将字典字典转换为数据框

[英]Convert a dictionary of dictionaries to dataframe

I am trying to convert a dictionary of dictionaries to DataFrame like this:我正在尝试将字典字典转换为 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 is working perfectly up until it encounters an empty dictionary. from_dict工作正常,直到遇到空字典。 It just skips that row and move to the next one.它只是跳过该行并移动到下一行。 So the dataframe created is missing last two entries.所以创建的数据框缺少最后两个条目。

How can I add 0 where the dictionary is empty?如何在字典为空的地方添加0

Such that the dataframe looks like this:这样数据框看起来像这样:

                   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

You can reindex with your dictionary keys and a fill_value of 0 before resetting the index:在重置索引fill_value reindex索引:

df_origcount = (pd.DataFrame.from_dict(objs, orient='index')
                  .reindex(objs, fill_value=0)
                  .reset_index()
               )

NB.注意。 avoid using inplace=True as much as possible, this doesn't enable to create pipelines.尽可能避免使用inplace=True ,这不能创建管道。

output:输出:

                                 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