パンダのデータフレームを階層型辞書に変換する方法


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

回答:


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

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

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 必要な結果を保持します。

弊社のサイトを使用することにより、あなたは弊社のクッキーポリシーおよびプライバシーポリシーを読み、理解したものとみなされます。
Licensed under cc by-sa 3.0 with attribution required.