如何将熊猫数据框转换为分层字典

时间:2020-01-20 02:57:27

标签: python pandas

我有以下熊猫数据框:

df1 = pd.DataFrame({'date': [200101,200101,200101,200101,200102,200102,200102,200102],'blockcount': [1,1,2,2,1,1,2,2],'reactiontime': [350,400,200,250,100,300,450,400]})

我正在尝试创建一个层次字典,将嵌入式字典的值作为列表,如下所示:

{200101: {1:[350, 400], 2:[200, 250]}, 200102: {1:[100, 300], 2:[450, 400]}}

我该怎么做?我得到的最接近的是使用此代码:

df1.set_index('date').groupby(level='date').apply(lambda x: x.set_index('blockcount').squeeze().to_dict()).to_dict()

哪个返回:

{200101: {1: 400, 2: 250}, 200102: {1: 300, 2: 400}}

3 个答案:

答案 0 :(得分:21)

这是使用pivot_table的另一种方式:

d = df1.pivot_table(index='blockcount',columns='date',
     values='reactiontime',aggfunc=list).to_dict()

print(d)

{200101: {1: [350, 400], 2: [200, 250]},
 200102: {1: [100, 300], 2: [450, 400]}}

答案 1 :(得分:7)

IIUC

    df1.groupby(['date','blockcount']).reactiontime.agg(list).unstack(0).to_dict()
{200101: {1: [350, 400], 2: [200, 250]}, 200102: {1: [100, 300], 2: [450, 400]}}

答案 2 :(得分:6)

您可以执行以下操作

df2 = df1.groupby(['date', 'blockcount']).agg(lambda x: pd.Series(x).tolist())

# Formatting the result to the correct format
dct = {}
for k, v in df2["reactiontime"].items():
  if k[0] not in dct: 
    dct[k[0]] = {}
  dct[k[0]].update({k[1]: v})

哪个生产

>>> {200101: {1: [350, 400], 2: [200, 250]}, 200102: {1: [100, 300], 2: [450, 400]}}

dct保存您需要的结果。