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

16

我有以下的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个回答

22

这里有另一种使用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]}}

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]}}

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保存了你需要的结果。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接