我想从字典列表中创建一个干净的pandas数据帧,其中字典中的键的值也可以是字典列表。
以下是我的初始列表:
[ {'product_id':1,
'categories': [{'toy_id':'x1', 'sales':50}, {'toy_id':'x2', 'sales':50}],
'buyers': [{'buyer_id':'y1' , 'buyer_age':22}, {'buyer_id':'y2' ,'buyer_age':31}]}]最初,我将列表转换为pandas dataframe
list_pd = pd.DataFrame(list)虽然这将我的列表转换为pandas数据帧,但其中有两个名为“类别”和“买家”的列,它们仍然是一个字典列表。我不确定如何将这些列转换为键名是列名、值在行中的列。我的最终结果如下所示:
____product_id____toy_id____sales____buyer_id____buyer_age
________1_________x1_______50_______y1__________22____
________1_________x2_______50_______y2__________31____以下是我尝试过的代码(我正在尝试将之前的代码再次转换为数据帧,认为它可能会破坏字典):
list_pd_2 = pd.DataFrame(list_pd)有人能帮上忙吗?
发布于 2020-05-06 01:20:03
一旦您像以前一样创建了list_pd,您就可以在categories和buyers列上使用explode,然后从每个分解列创建一个dataframe,保留原始索引,将dataframe和join都concat到列'product_id‘,如下所示:
s_cat = list_pd['categories'].explode()
s_buy = list_pd['buyers'].explode()
df_f = list_pd[['product_id']]\
.join(pd.concat([pd.DataFrame(s_cat.tolist(), index=s_cat.index),
pd.DataFrame(s_buy.tolist(), index=s_buy.index)],
axis=1))
print (df_f)
product_id toy_id sales buyer_id buyer_age
0 1 x1 50 y1 22
0 1 x2 50 y2 31发布于 2020-05-06 06:55:39
您可以使用pandas json_normalize函数:获取两个数据帧(类别和买家),并与pandas concat合并:
from pandas import json_normalize
categories = json_normalize(data,'categories','product_id')
buyers = json_normalize(data,'buyers')
pd.concat((categories,buyers),axis=1)
toy_id sales product_id buyer_id buyer_age
0 x1 50 1 y1 22
1 x2 50 1 y2 31https://stackoverflow.com/questions/61618801
复制相似问题