繁体   English   中英

使用 pandas dataframe 将列表列表的字典转换为字典的字典

[英]converting dict of list of lists to dict of dicts with pandas dataframe

尝试将 pandas dataframe 列从 a 转换为 b,如下所示 -

import pandas as pd

a = {'01AB': [["ABC",5],["XYZ",4],["LMN",1]],
     '02AB_QTY': [["Other",20],["not_Other",150],["another",15]]}

b = {'01AB': {"ABC":5,"XYZ":4,"LMN":1},
     '02AB_QTY': {"Other":20,"not_Other":150,"another":150}}

df = pd.DataFrame(a).to_dict(orient='dict')

print(df)

给我 -

{'01AB': {0: ['ABC', 5], 1: ['XYZ', 4], 2: ['LMN', 1]}, '02AB_QTY': {0: ['Other', 20], 1: ['not_Other', 150], 2: ['another', 15]}}

这样做更清洁的方法是什么? 这是我尝试过的,dict 'a' 只是为了创建 dataframe。我不想遍历它,必须遍历 pandas dataframe 中可用的列

import pandas as pd

a = {'01AB': [["ABC",5],["XYZ",4],["LMN",1]],
     '02AB_QTY': [["Other",20],["not_Other",150],["another",15]]}

b = {'01AB': {"ABC":5,"XYZ":4,"LMN":1},
     '02AB_QTY': {"Other":20,"not_Other":150,"another":150}}

df = pd.DataFrame(a)#.to_dict(orient='dict')

col_list = ["01AB", "02AB_QTY",]

for col in col_list:
#     print(df)

    df[col] = df[col].apply(lambda x: {} if x is None else {key: {v[0]:v[1] for v in list_item} for key, list_item in x})

display(df)
for key, list_item in a.items():
    a[key] = {v[0]:v[1] for v in list_item}

要么

b = {}
for key, list_item in a.items():
    b[key] = {v[0]:v[1] for v in list_item}

要么

b = {key: {v[0]:v[1] for v in list_item} for key, list_item in a.items()}

为了更清楚地举例,以下代码使用带有详细变量名的循环

a = {"01AB": [["ABC", 5], ["XYZ", 4], ["LMN", 1]],
     "02AB_QTY": [["Other", 20], ["not_Other", 150]]}

b = {"01AB": {"ABC": 5, "XYZ": 4, "LMN": 1},
     "02AB_QTY": {"Other": 20, "not_Other": 150}}

b1 = {}
for key1, list_of_key2_value in a.items():
    for key2, value in list_of_key2_value:
        b1.setdefault(key1, {}).update({key2: value})
assert b == b1

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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