【问题标题】:Convert a dictionary of dictionaries to dataframe将字典字典转换为数据框
【发布时间】:2022-07-05 23:18:29
【问题描述】:

我正在尝试将字典字典转换为 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

【问题讨论】:

    标签: python pandas dictionary


    【解决方案1】:

    在重置索引之前,您可以使用字典键 reindex 和 0 的 fill_value

    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
    

    【讨论】:

      猜你喜欢
      • 2021-06-19
      • 2019-07-18
      • 2019-08-02
      • 1970-01-01
      • 2019-02-22
      • 2018-11-07
      • 2017-07-16
      • 2020-12-22
      相关资源
      最近更新 更多