trying to convert pandas dataframe column from a to b as below -
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)
gives me -
{'01AB': {0: ['ABC', 5], 1: ['XYZ', 4], 2: ['LMN', 1]}, '02AB_QTY': {0: ['Other', 20], 1: ['not_Other', 150], 2: ['another', 15]}}
what will be the cleaner way to do this? This is what I have tried, dict 'a' is only to create the dataframe. I dont want to iterate through that, have to iterate through the column available in the 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)
CodePudding user response:
for key, list_item in a.items():
a[key] = {v[0]:v[1] for v in list_item}
OR
b = {}
for key, list_item in a.items():
b[key] = {v[0]:v[1] for v in list_item}
OR
b = {key: {v[0]:v[1] for v in list_item} for key, list_item in a.items()}
CodePudding user response:
To example be more clear, the following code using loop with verbose variable name
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