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


16

我有以下熊猫数据框:

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

Answers:


20

这是使用的另一种方式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

联合会

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

5

您可以执行以下操作

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

By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.