[python] 팬더 데이터 프레임을 계층 사전으로 변환하는 방법

다음과 같은 팬더 데이터 프레임이 있습니다.

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



답변

다음은 또 다른 방법입니다 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]}}


답변

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


답변

다음을 수행 할 수 있습니다.

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 필요한 결과를 보유합니다.


답변