簡體   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