简体   繁体   中英

Convert a dictionary of dictionaries to dataframe

I am trying to convert a dictionary of dictionaries to DataFrame like this:

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. 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?

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:

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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