【问题标题】:Extract information from nested dictionaries inside another dictionary从另一个字典中的嵌套字典中提取信息
【发布时间】:2018-09-01 21:09:30
【问题描述】:

数据集包含 25 列 500 行,其中一列是包含嵌套字典的“orderItems”,“orderItems”的所有键包含 1 - 15 个字典。随机取一行,例如:

dataset.orderItems[691581]

结果:

[{'product': 10152, 'price': 78.76, 'quantity': 1.0},
 {'product': 3584, 'price': 20.9, 'quantity': 1.0},
 {'product': 20308, 'price': 9.9, 'quantity': 1.0},
 {'product': 7619, 'price': 13.9, 'quantity': 1.0},
 {'product': 3795, 'price': 15.9, 'quantity': 1.0},
 {'product': 6504, 'price': 18.9, 'quantity': 2.0},
 {'product': 13720, 'price': 75.9, 'quantity': 1.0},
 {'product': 18419, 'price': 31.9, 'quantity': 1.0}]

想要创建 3 列:“产品”、“价格”和“数量”,以便它适合这些列中所有字典的所有信息。上面的示例将加上从“orderItems”的单个值中提取的 8 行。从“dataset.orderItems[691581]”中提取的价格、产品和数量信息将分为这 3 列,每列到他的适当列。请记住,有些键有 1 个字典,其他有 15 个(最大)

谁能帮帮我?

【问题讨论】:

  • 你尝试过什么,它到底有什么问题?
  • 我试过用pd.DataFrame.from_dict({(i): dataset.orderItems[i] for i in dataset.orderItems.keys()}, orient='index') 但是这段代码只带了15列,里面包含了字典 问题是我对Py很新,所以做不了太多。
  • 所以edit 包含minimal reproducible example 的问题。

标签: python pandas dictionary


【解决方案1】:

尝试以下方法:

list_df = []
for i, row in enumerate(df.values):
   df_values = df.loc[i,"orderitems"]
   for i, row in enumerate(df_values): 
        list_df.append(pd.DataFrame([row]))
 df_values_final=pd.concat(list_df)

【讨论】:

    【解决方案2】:

    这已返回您的行号列表。你可以这样处理:

    for dict_current in dataset.orderItems[691581]:
        i_prod_num = dict_current["product"]
        i_price = dict_current["price"]
        fl_quantity = dict_current["quantity"]
    

    接下来你要做什么取决于你想用这些值做什么。

    【讨论】:

    • 这段代码只取最后一个字典,因为一个循环承保另一个
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-06-02
    • 1970-01-01
    • 2021-11-09
    • 2020-09-23
    • 1970-01-01
    • 2018-01-29
    • 2020-01-21
    相关资源
    最近更新 更多